Friendiqa/source-linux/js/service.js

711 lines
42 KiB
JavaScript

// This file is part of Friendiqa
// https://git.friendi.ca/lubuwest/Friendiqa
// Copyright (C) 2020 Marco R. <thomasschmidt45@gmx.net>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// In addition, as a special exception, the copyright holders give
// permission to link the code of portions of this program with the
// OpenSSL library under certain conditions as described in each
// individual source file, and distribute linked combinations including
// the two.
//
// You must obey the GNU General Public License in all respects for all
// of the code used other than OpenSSL. If you modify file(s) with this
// exception, you may extend this exception to your version of the
// file(s), but you are not obligated to do so. If you do not wish to do
// so, delete this exception statement from your version. If you delete
// this exception statement from all source files in the program, then
// also delete it here.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//.pragma library
.import QtQuick.LocalStorage 2.0 as Sql
.import "qrc:/js/helper.js" as Helperjs
.import "qrc:/js/news.js" as Newsjs
// CONFIG FUNCTIONS
function initDatabase(database) { // initialize the database object
var db =Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
//print('initDatabase()'+database[0]+database[1]+database[2]+database[3])
db.transaction( function(tx) {
//var version=tx.executeSql('PRAGMA user_version');print(JSON.stringify(version.rows.item(0)))
tx.executeSql('CREATE TABLE IF NOT EXISTS imageData(username TEXT,id INT, created TEXT,edited TEXT, title TEXT, desc TEXT, album TEXT,filename TEXT, type TEXT, height INT, width INT, profile INT, link TEXT,location TEXT)');
tx.executeSql('CREATE TABLE IF NOT EXISTS config(server TEXT, username TEXT, password TEXT, imagestore TEXT, maxnews INT, timerInterval INT, newsViewType TEXT,isActive INT, permissions TEXT,maxContactAge INT,APIVersion TEXT,layout TEXT, addons TEXT)');
tx.executeSql('CREATE TABLE IF NOT EXISTS news(username TEXT, messagetype INT, text TEXT, created_at INT, in_reply_to_status_id INT, source TEXT, status_id INT, in_reply_to_user_id INT, geo TEXT,favorited TEXT, uid INT, statusnet_html TEXT, statusnet_conversation_id TEXT,friendica_activities TEXT, friendica_activities_self TEXT, attachments TEXT, friendica_owner TEXT)');
tx.executeSql('CREATE TABLE IF NOT EXISTS contacts(username TEXT, id INT, name TEXT, screen_name TEXT, location TEXT,imageAge INT, profile_image_url TEXT, description TEXT, profile_image BLOB, url TEXT, protected TEXT, followers_count INT, friends_count INT, created_at INT, favourites_count TEXT, utc_offset TEXT, time_zone TEXT, statuses_count INT, following TEXT, verified TEXT, statusnet_blocking TEXT, notifications TEXT, statusnet_profile_url TEXT, cid INT, network TEXT, isFriend INT, timestamp INT)');
// tx.executeSql('CREATE INDEX IF NOT EXISTS contact_id ON contacts(id)');
tx.executeSql('CREATE TABLE IF NOT EXISTS profiles(username TEXT, id INT, profiledata TEXT)');
tx.executeSql('CREATE TABLE IF NOT EXISTS groups(username TEXT, groupname TEXT, gid INT, members TEXT)');
tx.executeSql('CREATE TABLE IF NOT EXISTS events(username TEXT, id INT, start INT, end INT, allday INT, title TEXT, j INT, d TEXT, isFirst INT, uid INT, cid INT, uri TEXT, created INT, edited INT, desc TEXT, location TEXT, type TEXT, nofinish TEXT, adjust INT, ignore INT, permissions TEXT, guid INT, itemid INT, plink TEXT, authorName TEXT, authorAvatar TEXT, authorLink TEXT, html TEXT)');
tx.executeSql('CREATE TABLE IF NOT EXISTS globaloptions(k TEXT, v TEXT)');
tx.executeSql('CREATE TABLE IF NOT EXISTS friendshiprequests(username TEXT, id INT, usernamef TEXT, acct TEXT, display_name TEXT, locked TEXT, created_at INT, followers_count INT, following_count INT, statuses_count INT, note TEXT, url TEXT, avatar TEXT, avatar_static TEXT, header TEXT, header_static TEXT, emojis TEXT, moved TEXT, fields TEXT, bot TEXT, groupf TEXT, discoverable TEXT, last_status_at INT)');
tx.executeSql('CREATE TABLE IF NOT EXISTS hashtags(username TEXT, tag TEXT,date INT, statuses TEXT, ownership INT )');
tx.executeSql('CREATE TABLE IF NOT EXISTS drafts(username TEXT, header TEXT, statushtml TEXT, attachments TEXT, permissions TEXT, sendtime INT)');
})}
function cleanPermissions(oldperms){
var newperms=oldperms.replace("<","");newperms=newperms.replace(">","");newperms="["+newperms+"]";
var newpermArray=JSON.parse(newperms);
return (newpermArray)
}
function getEvents(database,login,rootwindow,callback){
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
Helperjs.friendicaWebRequest(login.server+"/cal/"+login.username+"/json",rootwindow,function(obj){
//Helperjs.friendicaRemoteAuthRequest(login,login.server+"/cal/"+login.username+"/json",login.server+"/profile/"+login.username,rootwindow,function(obj){
var events = JSON.parse(obj);
db.transaction( function(tx) {
for (var i=0;i<events.length;i++){
var permissions=[];
permissions.push(cleanPermissions(events[i].item.allow_cid));
permissions.push(cleanPermissions(events[i].item.allow_gid));
permissions.push(cleanPermissions(events[i].item.deny_cid));
permissions.push(cleanPermissions(events[i].item.deny_gid));
var result = tx.executeSql('SELECT * from events where username="'+login.username+'" AND id = '+events[i].id); // check for news id
if(result.rows.length === 1) {// use update
result = tx.executeSql('UPDATE events SET username="'+login.username+'", start="'+Date.parse(events[i].start)+'", end="'+Date.parse(events[i].end)+'", allday="'+Number(events[i].allday)+'", title="'+events[i].title+'", j="'+events[i].j+'", d="'+events[i].d+ '", isFirst="'+Number(events[i].isFirst)+'", uid="'+events[i].item.uid+'", cid="'+events[i].item.cid+'", uri="'+events[i].item.uri+'", created="'+ Date.parse(events[i].item.created)+'", edited="'+ Date.parse(events[i].item.edited)+'", desc="'+events[i].item.desc+'", location="'+events[i].item.location+'", type="'+events[i].item.type+'", nofinish="'+events[i].item.nofinish+'", adjust ="'+events[i].item.adjust+'", ignore="'+events[i].item.ignore+'", permissions="'+ JSON.stringify(permissions)+'", guid="'+events[i].item.guid+'", itemid="'+events[i].item.itemid+ '", plink="'+events[i].item.plink+ '", authorName="'+events[i].item["author-name"]+ '", authorAvatar="'+events[i].item["author-avatar"]+ '", authorLink="'+events[i].item["author-link"]+ '", html="'+Qt.btoa(events[i].html)+'" where username="'+login.username+'" AND id='+events[i].id);
} else {// use insert
result = tx.executeSql('INSERT INTO events (username,id,start,end,allday,title,j,d,isFirst,uid,cid,uri,created,edited,desc,location,type,nofinish,adjust,ignore,permissions,guid,itemid,plink,authorName,authorAvatar,authorLink,html) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', [login.username, events[i].id, Date.parse(events[i].start), Date.parse(events[i].end), events[i].allday, events[i].title, events[i].j, events[i].d, events[i].isFirst, events[i].item.uid, events[i].item.cid, events[i].item.uri, Date.parse(events[i].item.created), Date.parse(events[i].item.edited), events[i].item.desc, events[i].item.location, events[i].item.type, events[i].item.nofinish, events[i].item.adjust, events[i].item.ignore, JSON.stringify(permissions), events[i].item.guid, events[i].item.itemid, events[i].item.plink, events[i].item["author-name"], events[i].item["author-avatar"], events[i].item["author-link"], Qt.btoa(events[i].html)])}
callback()
}
})})}
function newscount(database, callback){
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
db.transaction( function(tx) {
var newscountrs = tx.executeSql('SELECT COUNT(*) from news');
var newscount = newscountrs.rows.item(0)["COUNT(*)"];
callback(newscount)
})
}
function eventsfromdb(database, username,callback){
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
var allcontacts=[];
allcontacts=Newsjs.getAllContacts(root.db,login.username);
db.transaction( function(tx) {
var eventrs=tx.executeSql('select * from events WHERE username="'+username+'" ORDER BY start ASC');
var eventArray=[];
var dayArray=[];
for(var i = 0; i < eventrs.rows.length; i++) {
eventArray.push(eventrs.rows.item(i));
if (eventArray[i].cid!=0){eventArray[i]["eventOwner"]=Newsjs.objFromArray(allcontacts,"cid",eventArray[i].cid);}
else{eventArray[i]["eventOwner"]=Newsjs.objFromArray(allcontacts,"isFriend",2);}
var startday=Math.floor((eventArray[i].start-new Date(eventArray[i].start).getTimezoneOffset() * 60 * 1000)/86400000);
var endday=Math.floor((eventArray[i].end-1-new Date(eventArray[i].end).getTimezoneOffset() * 60 * 1000)/86400000);if (endday<startday){endday=startday}
eventArray[i]["startday"]=startday;eventArray[i]["endday"]=endday;
dayArray.push(startday);
if (endday>startday){
for (var j=startday+1;j<endday+1;j++){dayArray.push(j)}
}
}
callback(eventArray,dayArray)});
}
function requestFriendsEvents(login,friend,rootwindow,callback){
// get calendar JSON object of contact without user and password
Helperjs.friendicaWebRequest(friend.replace("profile","cal")+"/json",rootwindow,function(calhtml){
//print(calhtml);
var eventarray=[];var eventdays=[];
var events=JSON.parse(calhtml);
for (var i=0;i<events.length;i++){
var permissions=[];
permissions.push(cleanPermissions(events[i].item.allow_cid));
permissions.push(cleanPermissions(events[i].item.allow_gid));
permissions.push(cleanPermissions(events[i].item.deny_cid));
permissions.push(cleanPermissions(events[i].item.deny_gid));
var event ={}
event.start=Date.parse(events[i].start);event.end=Date.parse(events[i].end);
event.allday=events[i].allday; event.title=events[i].title; event.j=events[i].j;
event.d=events[i].d; event.isFirst=events[i].isFirst; event.uid=events[i].item.uid;
event.cid=events[i].item.cid; event.uri=events[i].item.uri;
event.created=Date.parse(events[i].item.created); event.edited=Date.parse(events[i].item.edited);
event.desc=events[i].item.desc; event.location=events[i].item.location; event.type=events[i].item.type;
event.nofinish=events[i].item.nofinish; event.adjust =events[i].item.adjust; event.ignore=events[i].item.ignore;
event.permissions=JSON.stringify(permissions); event.guid=events[i].item.guid;
event.itemid=events[i].item.itemid; event.plink=events[i].plink; event.authorName=events[i].item["author-name"];
event.authorAvatar=events[i].item["author-avatar"]; event. authorLink=events[i].item["author-link"];
event.html=Qt.btoa(events[i].html);
eventarray.push(event);
// var offsetTime = new Date().getTimezoneOffset() * 60 * 1000;print(new Date(event.start).toLocaleString()+"Zeitverschiebung:"+offsetTime)
// var time = event.start - offsetTime;
eventdays.push(Math.floor(event.start/(24*60*60*1000)))
}
//print(JSON.stringify(eventarray));
callback(eventarray,eventdays)
})
}
function newRequestFriendsEvents(login,friend,rootwindow,callback){
// get calendar JSON object of contact with remoteAuth or without user and password
if(friend.isFriend==1){
Helperjs.friendicaRemoteAuthRequest(login,friend.url.replace("profile","cal")+"/json",friend.url,rootwindow,function(calhtml){
getEventsFromHtml(calhtml,rootwindow,callback)})
}
else{
Helperjs.friendicaWebRequest(friend.url.replace("profile","cal")+"/json",rootwindow,function(calhtml){
getEventsFromHtml(calhtml,rootwindow,callback)})
}
}
function getEventsFromHtml(calhtml,rootwindow,callback){
var eventarray=[];var eventdays=[];
var events=JSON.parse(calhtml);
for (var i=0;i<events.length;i++){
var permissions=[];
permissions.push(cleanPermissions(events[i].item.allow_cid));
permissions.push(cleanPermissions(events[i].item.allow_gid));
permissions.push(cleanPermissions(events[i].item.deny_cid));
permissions.push(cleanPermissions(events[i].item.deny_gid));
var event ={}
event.start=Date.parse(events[i].start);event.end=Date.parse(events[i].end);
event.allday=events[i].allday; event.title=events[i].title; event.j=events[i].j;
event.d=events[i].d; event.isFirst=events[i].isFirst; event.uid=events[i].item.uid;
event.cid=events[i].item.cid; event.uri=events[i].item.uri;
event.created=Date.parse(events[i].item.created); event.edited=Date.parse(events[i].item.edited);
event.desc=events[i].item.desc; event.location=events[i].item.location; event.type=events[i].item.type;
event.nofinish=events[i].item.nofinish; event.adjust =events[i].item.adjust; event.ignore=events[i].item.ignore;
event.permissions=JSON.stringify(permissions); event.guid=events[i].item.guid;
event.itemid=events[i].item.itemid; event.plink=events[i].plink; event.authorName=events[i].item["author-name"];
event.authorAvatar=events[i].item["author-avatar"]; event. authorLink=events[i].item["author-link"];
event.html=Qt.btoa(events[i].html);
eventarray.push(event);
// var offsetTime = new Date().getTimezoneOffset() * 60 * 1000;print(new Date(event.start).toLocaleString()+"Zeitverschiebung:"+offsetTime)
// var time = event.start - offsetTime;
eventdays.push(Math.floor(event.start/(24*60*60*1000)))
}
//print(JSON.stringify(eventarray));
callback(eventarray,eventdays)
}
function savePermissions(database,obj) { // stores config to DB
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
var permissions=JSON.stringify(obj)
db.transaction( function(tx) {
var result = tx.executeSql( 'UPDATE config SET permissions="'+permissions+'" WHERE username="'+obj.username +'"');
})
}
function storeConfig(database,obj) { // stores config to DB
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
db.transaction( function(tx) {
//print(JSON.stringify(obj));
var result = tx.executeSql('SELECT * from config WHERE username="'+obj.username+'"');
if(result.rows.length === 1) {// use update
var result2 = tx.executeSql('UPDATE config SET server="'+obj.server+'",password="'+obj.password+'", imagestore="'+obj.imagestore+'", maxnews=0, timerInterval=0, newsViewType="'+obj.newsViewType+'", isActive=0 WHERE username="'+obj.username +'"');
var result3 = tx.executeSql('UPDATE config SET isActive=1 WHERE username !="'+obj.username +'"');
} else {// use insert print('... does not exists, create it')
var result2 = tx.executeSql('INSERT INTO config VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)', [obj.server, obj.username, obj.password, obj.imagestore, 0, 0,obj.newsViewType,0,"[[],[],[],[]]",0,"","",""]);
var result3 = tx.executeSql('UPDATE config SET isActive=1 WHERE username !="'+obj.username +'"');
}
})}
function showServerConfig(url,rootwindow,callback){//print(url);
Helperjs.friendicaWebRequest(url+"/api/statusnet/config",rootwindow, function (obj){
var serverconfig = JSON.parse(obj);
var serverConfigString="import QtQuick 2.0; import QtQuick.Dialogs 1.2; MessageDialog{ visible: true; title:'Server';standardButtons: StandardButton.Ok;text: 'Name: "+serverconfig.site.name+"\nLanguage: "+serverconfig.site.language+
"\nEmail: "+serverconfig.site.email+"\nTimezone: "+serverconfig.site.timezone+"\nClosed: "+serverconfig.site.closed+
"\nText limit: "+serverconfig.site.textlimit+"\nShort Url length: "+serverconfig.site.shorturllength+
"\nFriendica version: "+serverconfig.site.friendica.FRIENDICA_VERSION+"\nDFRN version: "+serverconfig.site.friendica.DFRN_PROTOCOL_VERSION +
"\nDB Update version: "+serverconfig.site.friendica.DB_UPDATE_VERSION+"'}";
callback(serverConfigString)
})}
function checkLogin(login,rootwindow,callback){
// check server with given credentials
try {Helperjs.friendicaRequest(login,"/api/account/verify_credentials",rootwindow, function (obj){
var account = JSON.parse(obj);
callback(account)
})}
catch(e){}
}
function requestProfile(login,database,rootwindow,callback){
// return profile data
Helperjs.friendicaRequest(login,"/api/friendica/profile/show", rootwindow,function (obj){
var profiledata=JSON.parse(obj);
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
for (var i=0;i<profiledata.profiles.length;i++){
//print('store profile data for '+JSON.stringify(profiledata.profiles[i]));
db.transaction( function(tx) {
var result = tx.executeSql('SELECT * from profiles where username="'+login.username+'" AND id = '+profiledata.profiles[i].profile_id); // check for profile id
if(result.rows.length === 1) {// use update
result = tx.executeSql('UPDATE profiles SET profiledata="'+ Qt.btoa(JSON.stringify(profiledata.profiles[i]))+'" WHERE username="'+login.username+'" AND id='+parseInt(profiledata.profiles[i].profile_id));
} else {// use insert
result = tx.executeSql('INSERT INTO profiles (username,id,profiledata) VALUES (?,?,?)', [login.username,profiledata.profiles[i].profile_id,Qt.btoa(JSON.stringify(profiledata.profiles[i]))])}
});
}
var profile=profiledata.friendica_owner;
profile.isFriend=2;
var profilearray=[];profilearray.push(profile);
callback(profilearray)
});
}
function getServerConfig(database,login,rootwindow,callback){
// check server with given credentials
try {Helperjs.friendicaRequest(login,"/api/statusnet/config",rootwindow, function (obj){
var serverconfig = JSON.parse(obj);
var serverconfigString="import QtQuick 2.0; import QtQuick.Dialogs 1.2; MessageDialog{ visible: true; title:'Server';standardButtons: StandardButton.Ok;text: 'SUCCESS! \nName: "+serverconfig.site.name+"\nLanguage: "+serverconfig.site.language+
"\nEmail: "+serverconfig.site.email+"\nTimezone: "+serverconfig.site.timezone+"\nClosed: "+serverconfig.site.closed+
"\nText limit: "+serverconfig.site.textlimit+"\nShort Url length: "+serverconfig.site.shorturllength+
"\nFriendica version: "+serverconfig.site.friendica.FRIENDICA_VERSION+"\nDFRN version: "+serverconfig.site.friendica.DFRN_PROTOCOL_VERSION +
"\nDB Update version: "+serverconfig.site.friendica.DB_UPDATE_VERSION+"'}";
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
db.transaction( function(tx) {
var result = tx.executeSql('UPDATE config SET APIVersion="'+ serverconfig.site.friendica.FRIENDICA_VERSION+'" WHERE username="'+login.username +'"')})
callback(serverconfigString);
})}
catch (e){callback (e);
}}
function readConfig(database,callback,filter,filtervalue) { // reads config
if (filter){var where = " WHERE "+ filter +" = '" + filtervalue+"'"} else { var where=""}
//print("readConfig");
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3],initDatabase(database));
db.transaction( function(tx) {
var tables = tx.executeSql("SELECT * FROM sqlite_master WHERE type='table'");
if (tables.rows.length==0){print("no database");callback("")} else {
var rs = tx.executeSql('select * from config'+where);
var rsArray=[];
if (rs.rows.length>0){
for(var i = 0; i < rs.rows.length; i++) {
rsArray.push(rs.rows.item(i))
}
var rsObject={server:rsArray[0].server,username:rsArray[0].username, password:rsArray[0].password,imagestore:rsArray[0].imagestore,isActive:rsArray[0].isActive, newsViewType:rsArray[0].newsViewType,permissions:JSON.parse(rsArray[0].permissions),maxContactAge:rsArray[0].maxContactAge,APIVersion:rsArray[0].APIVersion,addons:rsArray[0].addons};
if (rsObject.newsViewType!="" && rsObject.newsViewType!=null){updateNewsviewtype(database,rsObject.newsViewType)}
} else {var rsObject=""}
callback(rsObject)}}
)
}
function readAllLogins(database,callback) { // reads config
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3],initDatabase(database));
db.transaction( function(tx) {
var tables = tx.executeSql("SELECT * FROM sqlite_master WHERE type='table'");
if (tables.rows.length==0){print("no database");callback("")} else {
var rs = tx.executeSql('select * from config');
var rsArray=[];
if (rs.rows.length>0){
for(var i = 0; i < rs.rows.length; i++) {
rsArray.push(rs.rows.item(i));
rsArray[i].permissions=JSON.parse(rsArray[i].permissions)
}
}
}
callback(rsArray)}
)
}
function readActiveConfig(database){
var obj="";
readConfig(database,function(config){obj=config},"isActive", 0);
return obj;
}
function setDefaultOptions(database){
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
db.transaction( function(tx) {
var rs = tx.executeSql('INSERT INTO globaloptions (k,v) VALUES ("newsViewType","Conversations")');
})
}
function readGlobaloptions(database,callback){
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
var go=({});
db.transaction( function(tx) {
var rs = tx.executeSql('select * from globaloptions');
for (var r=0; r<rs.rows.length; r++){
go[rs.rows.item(r).k]=rs.rows.item(r).v
}
callback(go)
})
}
function readGO(database){
var obj;
readGlobaloptions(database,function(go){obj=go});
return obj
}
function updateglobaloptions(database,key,value){
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
db.transaction( function(tx) {
var result = tx.executeSql('SELECT * from globaloptions where k="'+key+'"'); // check for key
if(result.rows.length === 1) {// use update
result = tx.executeSql('UPDATE globaloptions SET v="'+value+'" WHERE k="'+key+'"')
} else {// use insert
result = tx.executeSql('INSERT INTO globaloptions (k,v) VALUES (?,?)', [key,value])
}
})
root.globaloptions[key]=value;
}
function deleteConfig(database,userobj,callback) { // delete user data from DB
if (userobj){var where = " WHERE username='"+ userobj.username+"' and server='"+userobj.server+"'";} else { return "no user selected!";}
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
if(!db) { return; }
db.transaction( function(tx) {
var rs1 = tx.executeSql('delete from config'+where);
var rs2 = tx.executeSql("delete from news WHERE username='"+ userobj.username+"'");
var rs3 = tx.executeSql("delete from contacts WHERE username='"+ userobj.username+"'");
var rs4 = tx.executeSql("delete from imageData WHERE username='"+ userobj.username+"'");
var rs5 = tx.executeSql("delete from groups WHERE username='"+ userobj.username+"'");
var rs5 = tx.executeSql("delete from events WHERE username='"+ userobj.username+"'");
callback();
})
}
function updateNewsviewtype(database, newsViewtype){
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
if(!db) { return; }
db.transaction( function(tx) {
var rs1 = tx.executeSql('INSERT INTO globaloptions (k,v) VALUES (?,?)', ["newsViewType",newsViewtype])
var rs2 = tx.executeSql('UPDATE config SET newsViewType=""');
//Helperjs.showMessage(qsTr("Changelog"),qsTr("Setting view type of news has moved from account page to config page."),root)
})
}
function cleanNews(database,callback){
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
db.transaction( function(tx) {
var maxnewsrs = tx.executeSql("SELECT v FROM globaloptions WHERE k='max_news'");
var maxnews=1000; if(maxnewsrs.rows.length>0){ maxnews=maxnewsrs.rows.item(0).v};
for (var i=0; i<6;i++){
if (i!=0){var maxnewsa=maxnews/5}else{maxnewsa=maxnews}
var newscountrs = tx.executeSql('SELECT COUNT(*) from news WHERE messagetype='+i);
var newscount = 0;
if (newscountrs.rows.length>0){newscount=newscountrs.rows.item(0)["COUNT(*)"]};//print(i+" "+maxnewsa+" newscount "+newscount)
if (newscount>maxnewsa){
var lastvalidtimers= tx.executeSql('SELECT DISTINCT created_at FROM news WHERE messagetype='+i+' ORDER BY created_at ASC LIMIT ' +(newscount-maxnewsa));
var lastvalidtime=lastvalidtimers.rows.item(newscount-maxnewsa-1).created_at;
var deleters = tx.executeSql('DELETE from news WHERE messagetype='+i+' AND created_at<='+lastvalidtime)}
}
callback()
})
}
function cleanContacts(login,database,callback){
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
db.transaction( function(tx) {
var oldestnewsrs= tx.executeSql('SELECT created_at FROM news WHERE username="'+login.username+'" AND messagetype=0 ORDER BY created_at ASC LIMIT 1');
if (oldestnewsrs.rows.length>0){ var oldestnewsTime=oldestnewsrs.rows.item(0).created_at- 604800000;} else{var oldestnewsTime=0} //contacts can be 7 days old
//print(login.username+" älteste news: "+ oldestnewsTime);
var result = tx.executeSql('SELECT * from contacts WHERE username="'+login.username+'" AND isFriend=0 AND imageAge<'+oldestnewsTime); // check for friends
//print ("Contact result length: "+ result.rows.length)
for (var i=0;i<result.rows.length;i++){
filesystem.rmFile(result.rows.item(i).profile_image);
var deleters = tx.executeSql('DELETE from contacts WHERE username="'+login.username+'" AND url="'+result.rows.item(i).url+'"');
}
callback()
})
}
function cleanHashtags(database,callback){
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
db.transaction( function(tx) {
var tagcountrs = tx.executeSql('SELECT COUNT(*) from hashtags');
var tagcount = 0;
if (tagcountrs.rows.length>0){tagcount=tagcountrs.rows.item(0)["COUNT(*)"]};
if (tagcount>50){
var lastvaliddaters= tx.executeSql('SELECT DISTINCT date FROM hashtags ORDER BY date ASC LIMIT ' +(tagcount-50));
var lastvaliddate=lastvaliddaters.rows.item(tagcount-49).date;
var deleters = tx.executeSql('DELETE from hashtags WHERE date<='+lastvaliddate)}
callback()
})
}
function updateContactInDB(login,database,isFriend,contact){// for newstab and friendstab
var currentTime=Date.now();
var image_timestamp=0;
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
db.transaction( function(tx) {
var imagename_helper=[];
imagename_helper=contact.profile_image_url.split('?');//print("substring: "+JSON.stringify(imagename_helper)+imagename_helper[0].substring(imagename_helper[0].lastIndexOf("/")+1, imagename_helper[0].length))
try {parseInt(image_timestamp=imagename_helper[1].substring(imagename_helper[1].indexOf("ts=")+3,imagename_helper[1].length))} catch(e){};
var result;
result = tx.executeSql('SELECT * from contacts where username="'+login.username+'" AND url = "'+contact.url+'"'); // check for news url
if(result.rows.length === 1) {// use update
result = tx.executeSql('UPDATE contacts SET id='+contact.id+', name="'+Qt.btoa(contact.name)+'", screen_name="'+contact.screen_name+'", location="'+contact.location+'",imageAge='+currentTime+', profile_image_url="'+contact.profile_image_url+'", description="'+Qt.btoa(contact.description)+'", protected="'+contact.protected+'", followers_count='+contact.followers_count+', friends_count='+contact.friends_count+', created_at="'+ contact.created_at+'", favourites_count="'+contact.favorites_count+'", utc_offset="'+contact.utc_offset+'", time_zone="'+contact.time_zone+'", statuses_count='+contact.statuses_count+', following="'+contact.following+'", verified ="'+contact.verified+'", statusnet_blocking="'+contact.statusnet_blocking+'", notifications="'+contact.notifictions+'", statusnet_profile_url="'+contact.statusnet_profile_url+'", cid='+contact.cid+', network="'+contact.network+'", isFriend='+isFriend+', timestamp='+ currentTime+' where username="'+login.username+'" AND url="'+contact.url+'"');
} else {// use insert
result = tx.executeSql('INSERT INTO contacts VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', [login.username,contact.id,Qt.btoa(contact.name),contact.screen_name,contact.location,currentTime,contact.profile_image_url, Qt.btoa(contact.description),"",contact.url,contact.protected,contact.followers_count, contact.friends_count,contact.created_at,contact.favorites_count,contact.utc_offset,contact.time_zone,contact.statuses_count,contact.following,contact.verfied,contact.statusnet_blocking,contact.notifications,contact.statusnet_profile_url,contact.cid,contact.network,isFriend,image_timestamp]);}
});
}
function processNews(api,data){
try{var newslist=JSON.parse(data)} catch(e){newsBusy.running=false;};
if (api=="/api/users/show"){
var usermessages=[];
usermessages.push(newslist.status);
newslist=usermessages;
}
if (data==""){}
else if (typeof(newslist)=='undefined'){
Helperjs.showMessage(qsTr("Undefined Array Error"),"API:\n" +login.server+api+"\n Return: \n"+data,root)
}
else if (newslist.hasOwnProperty('status')){
Helperjs.showMessage(qsTr("JSON status Error"),"API:\n" +login.server+api+"\n Return: \n"+data,root)
}
else if (!(Array.isArray(newslist))){
replytimer.restart()
}
else {
var allcontacts=[];
allcontacts=Newsjs.getAllContacts(db,login.username);
if (api=="/api/direct_messages/all" || api=="/api/direct_messages/conversation"){
for (var n in newslist){
newslist[n].created_at=Date.parse(Newsjs.cleanDate(newslist[n].created_at));
newslist[n].messagetype=1;
newslist[n].source=" Friendica";
newslist[n].status_id=newslist[n].id;
newslist[n].uid=newslist[n].sender.id;
newslist[n].statusnet_conversation_id=newslist[n].friendica_parent_uri;
newslist[n].user=cleanUser(newslist[n].sender);
newslist[n].friendica_owner=newslist[n].user;
newslist[n].friendica_author=newslist[n].user;
newslist[n].statusnet_html=newslist[n].text;
newslist[n].in_reply_to_user_id=newslist[n].recipient_id
if(newslist[n].in_reply_to_user_id){newslist[n].reply_user=Newsjs.objFromArray(allcontacts,"id",newslist[n].in_reply_to_user_id)}
}}
else if (api=="/api/friendica/notifications"){
for (var n in newslist){
newslist[n].created_at=Date.parse(newslist[n].date);
newslist[n].messagetype=2;
newslist[n].user=Newsjs.objFromArray(allcontacts,"url",newslist[n].url)
if (newslist[n].user==false){
newslist[n].user={"profile_image_url": newslist[n].photo,"name": newslist[n].name," url":newslist[n].url, "created_at":newslist[n].date};
newslist[n].user=cleanUser(newslist[n].user);
}
newslist[n].friendica_author=newslist[n].user;
newslist[n].friendica_owner=newslist[n].user;
newslist[n].statusnet_html=newslist[n].msg_html;
newslist[n].text=newslist[n].msg;
}
}
else {//if(api!="/api/statuses/user_timeline"){
var chatlist=[];
var conversationIds=[];
var commentCount=[];
for (var n in newslist){
if (newslist[n]!=null){
newslist[n].created_at=Date.parse(Newsjs.cleanDate(newslist[n].created_at));
if (api=="/api/statuses/replies"){newslist[n].messagetype=3}else{newslist[n].messagetype=0;}
newslist[n].friendica_author=cleanUser(newslist[n].friendica_author);
newslist[n].user=cleanUser(newslist[n].user);
if (newslist[n].friendica_title!="") {newslist[n].statusnet_html="<b>"+newslist[n].friendica_title +"</b><br><br>"+newslist[n].friendica_html;}
else{newslist[n].statusnet_html=newslist[n].friendica_html}
if(newslist[n].in_reply_to_user_id){newslist[n].reply_user=Newsjs.objFromArray(allcontacts,"id",newslist[n].in_reply_to_user_id)}
if(newslist[n].hasOwnProperty('friendica_activities')){
for (var m in newslist[n].friendica_activities.like){
newslist[n].friendica_activities.like[m]=cleanUser(newslist[n].friendica_activities.like[m]);
}
for (var o in newslist[n].friendica_activities.dislike){
newslist[n].friendica_activities.dislike[o]=cleanUser(newslist[n].friendica_activities.dislike[o]);
}
for (var p in newslist[n].friendica_activities.attendyes){
newslist[n].friendica_activities.attendyes[p]=cleanUser(newslist[n].friendica_activities.attendyes[p]);
}
for (var q in newslist[n].friendica_activities.attendno){
newslist[n].friendica_activities.attendno[q]=cleanUser(newslist[n].friendica_activities.attendno[q]);
}
for (var r in newslist[n].friendica_activities.attendmaybe){
newslist[n].friendica_activities.attendmaybe[r]=cleanUser(newslist[n].friendica_activities.attendmaybe[r]);
}
}
if(!(newslist[n].hasOwnProperty('friendica_author'))){
newslist[n].friendica_author=newslist[n].user
}
var conversationindex=conversationIds.indexOf(newslist[n].statusnet_conversation_id);
//fill chatlist
if (conversationindex==-1){
chatlist.push(newslist[n]);
conversationIds.push(newslist[n].statusnet_conversation_id);
commentCount.push(1);
} else{
commentCount[conversationindex]=commentCount[conversationindex]+1;
chatlist[conversationindex]=newslist[n];
}
}
}
//enrich chatlist with old entries
for (var count in chatlist){ //print("chat "+JSON.stringify(chatlist[count])+" count: "+commentCount[count])
//chatlist[count].newscount=commentCount[count]
if (chatlist[count].id_str!==chatlist[count].statusnet_conversation_id){
try{
Newsjs.oldchatfromdb(db,login.username,chatlist[count].statusnet_conversation_id,chatlist[count].id,allcontacts,function(oldpost,oldcount){
chatlist[count]=oldpost;
chatlist[count].newscount=oldcount+commentCount[count];
//print("JSON "+chatlist[count].statusnet_conversation_id+" "+chatlist[count].id+JSON.stringify(oldpost))
})
}catch(e){print(e)}
}
else{chatlist[count].newscount=commentCount[count]}
}
}
if (api=="/api/conversation/show"|| api=="/api/direct_messages/conversation"){
newslist.reverse();
newstab.conversation=newslist
}
else if (api=="/api/statuses/user_timeline" || api=="/api/users/show"){
root.contactposts=newslist
}
else if ((api!="/api/direct_messages/all")&&(api!="/api/friendica/notifications")&&(newstab.newstabstatus==="Conversations")){
showNews(chatlist);root.news=newslist
}
else {
showNews(newslist);root.news=newslist
};
var newstabarray=["Conversations","Favorites","Timeline","DirectMessage","Replies"];
if (newstabarray.indexOf(newstab.newstabstatus)>-1){contacttimer.start()}
}
}
function cleanUser(user){
user.created_at=Date.parse(Newsjs.cleanDate(user.created_at));
var imagehelper1=user.profile_image_url.split("?");
var imagehelper2=imagehelper1[0].substring(imagehelper1[0].lastIndexOf("/")+1,imagehelper1[0].length);
var imagehelper3=login.imagestore+"contacts/"+user.screen_name+"-"+imagehelper2
if(filesystem.fileexist(imagehelper3)){user.profile_image=imagehelper3}else {user.profile_image=""}
return user
}
function updateView(viewtype){
//messageSend.state="";
//newsBusy.running=true;
//downloadNotice.text="xhr start "+Date.now()
switch(viewtype){
case "Conversations":
Newsjs.getLastNews(login,db,function(lastnews){
xhr.setLogin(login.username+":"+Qt.atob(login.password));
xhr.setUrl(login.server);
xhr.setApi("/api/statuses/friends_timeline");
xhr.clearParams();
xhr.setParam("since_id",lastnews);
xhr.setParam("count",50)});
break;
case "Timeline":
var lastnews=Newsjs.getLastNews(login,db,function(lastnews){
xhr.setLogin(login.username+":"+Qt.atob(login.password));
xhr.setUrl(login.server);
xhr.setApi("/api/statuses/friends_timeline");
xhr.clearParams();
xhr.setParam("since_id",lastnews);
xhr.setParam("count",50)
});
break;
case "Search":
xhr.setLogin(login.username+":"+Qt.atob(login.password));
xhr.setUrl(login.server);
xhr.setApi("/api/search");
break;
case "Notifications":
xhr.setLogin(login.username+":"+Qt.atob(login.password));
xhr.setUrl(login.server);
xhr.setApi("/api/friendica/notifications");
xhr.clearParams();
break;
case "Direct Messages":
xhr.setLogin(login.username+":"+Qt.atob(login.password));
xhr.setUrl(login.server);
xhr.setApi("/api/direct_messages/all");
xhr.clearParams();
break;
case "Public Timeline":
xhr.setLogin(login.username+":"+Qt.atob(login.password));
xhr.setUrl(login.server);
xhr.setApi("/api/statuses/public_timeline");
xhr.clearParams();
break;
case "Favorites":
xhr.setLogin(login.username+":"+Qt.atob(login.password));
xhr.setUrl(login.server);
xhr.setApi("/api/favorites");
xhr.clearParams();
break;
case "Replies":
xhr.setLogin(login.username+":"+Qt.atob(login.password));
xhr.setUrl(login.server);
xhr.setApi("/api/statuses/replies");
xhr.clearParams();
break;
default:
Newsjs.getLastNews(login,db,function(lastnews){
xhr.setLogin(login.username+":"+Qt.atob(login.password));
xhr.setUrl(login.server);
xhr.setApi("/api/statuses/friends_timeline");
xhr.clearParams();
xhr.setParam("since_id",lastnews);
xhr.setParam("count",50)
newstab.newstabstatus="Conversations";
});
}
xhr.get();
if (viewtype==="Conversations"){Newsjs.allchatsfromdb(db,login.username,function(temp){
newsStack.allchats=temp
})}
if ((osSettings.osType=="Android") && root.globaloptions.hasOwnProperty("syncinterval") && root.globaloptions.syncinterval !=null && root.globaloptions.syncinterval !=0){
//alarm.setAlarm(root.globaloptions.syncinterval);
setBackgroundsync()
}
}
function showGroups(){
Helperjs.readData(db,"groups",login.username,function(groups){
var groupitems="";
for (var i=0;i<groups.length;i++){
groupitems=groupitems+"MenuItem{text:'"+groups[i].groupname+"'; onTriggered: Service.getGroupnews("+groups[i].gid+")}"
}
var menuString="import QtQuick.Controls 2.12; import 'qrc:/js/service.js' as Service; Menu {"+groupitems+"}";
var grouplistObject=Qt.createQmlObject(menuString,newsStack,"groupmenuOutput");
grouplistObject.popup()
})
}
function setBackgroundsync(){
Helperjs.readData(db,"globaloptions","",function(lastsync){
if((lastsync.length>0)&&((parseFloat(lastsync[0]["v"])+120)<(Date.now()/1000))){
alarm.setAlarm(root.globaloptions.syncinterval);
}
},"k","lastsync")
}
function getGroupnews(list){
newstab.newstabstatus="Group news";
newsBusy.running=true;
xhr.setLogin(login.username+":"+Qt.atob(login.password));
xhr.setUrl(login.server);
xhr.setApi("/api/lists/statuses");
xhr.clearParams();
xhr.setParam("list_id",list)
xhr.get();
}