Friendiqa/v0.002/Develop/source-android/js/service.js

222 lines
13 KiB
JavaScript

//.pragma library
.import QtQuick.LocalStorage 2.0 as Sql
.import "qrc:/js/helper.js" as Helperjs
.import "qrc:/js/news.js" as Newsjs
// IMAGE FUNCTIONS
function requestList(login,database,rootwindow,callback) {
//get list of own images and call download function
Helperjs.friendicaRequest(login,"/api/friendica/photos/list", rootwindow,function (helperobject){
print("return"+helperobject);
var obj=JSON.parse(helperobject);
Helperjs.readField("id",database,"imageData",login.username,function(AllStoredImages){
if (AllStoredImages.length>0){
for(var i=0;i< AllStoredImages.length;i++){
var position=Helperjs.inArray(obj,"resourceID",AllStoredImages[i]);
if (position>-1){obj.splice(position,1)}
//obj.splice(obj.indexOf(AllStoredImages[i]),1);// list of objects instead of list!!!
}
}}
);
callback(obj);
})}
function dataRequest(login,photoID,database,rootwindow) {
// check if image exist and call download function
Helperjs.friendicaRequest(login,"/api/friendica/photo?photo_id="+photoID, rootwindow, function (image){
try{ if(image==""){currentImageNo=currentImageNo+1}else{
var obj = JSON.parse(image);
print('storeData() for ' + JSON.stringify(obj));
// try{sprite.destroy();}catch(e){}
// if (obj["link"]["0"]){var source=obj["link"]["0"]} else {var source=obj["link"]["4"]}//source for profile picture or original size
// print("Source"+source);
obj["source"]=source;
var filename=obj.filename;
if (filename==""){// check if file has any filename
if (obj.type=="image/jpeg") {obj["filename"]=obj["id"]+".jpg"}
else if (obj.type=="image/png") {obj["filename"]=obj["id"]+".png"}
}
// check if text name has valid image format ending, otherwise append appropriate ending
if(["jpg","png"].indexOf(obj["filename"].substring(obj["filename"].lastIndexOf(".")+1,obj["filename"].length))==-1){
print("falscheEndung: "+obj["filename"].substring(obj["filename"].lastIndexOf(".")+1,obj["filename"].length));
{ if (obj.type=="image/jpeg") {obj["filename"]=obj["filename"]+".jpg"}
else if (obj.type=="image/png") {obj["filename"]=obj["filename"]+".png"}
}
print("obj.Filename: "+obj["filename"]+" filename: "+filename)
}
saveImage(obj,login.imagestore+'albums/'+obj.album,function(obj,sprite){
//sprite.destroy(500);
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
db.transaction( function(tx) {
print('... check if a object exists: '+obj["id"])
var result = tx.executeSql('SELECT * from imageData where id = "'+obj["id"]+'"');
if(result.rows.length === 1) {// use update
print(obj["id"] +' exists, update it')
result = tx.executeSql('UPDATE imageData SET username ="' +login.username+ '",id="'+obj.id+'", created="'+obj.created+'", edited="'+obj.edited+'", profile="'+obj.profile+'", link="'+obj["link"]["4"]+'", filename="'+obj.filename+'",title="'+obj.title+'", desc="'+obj.desc+'", type="'+obj.type+'", width="'+obj.width+'", height="'+obj.height+'", album="'+obj.album+'", location="file://'+login.imagestore+'albums/'+obj.album+'/" where id="'+obj["id"]+'"');
} else {// use insert print('... does not exists, create it')
result = tx.executeSql('INSERT INTO imageData VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)', [login.username,obj.id,obj.created,obj.edited, obj.title, obj.desc, obj.album, obj.filename, obj.type, obj.height, obj.width,obj. profile,obj["link"]["4"],'file://'+login.imagestore+'albums/'+obj.album+"/"]);
print("Inserted");}
})})}}
catch (e){print("Data retrieval failure! "+ e+obj);}
})}
function saveImage(obj,storagedirectory,callback) {
// create image component from base64 code and save it
print("Storing "+storagedirectory+"/"+obj.filename+obj.width+"x"+obj.height);
var maxSize=Math.max(fotostab.width,fotostab.height);
var helpwidth=(obj.width<maxSize)?obj.width:maxSize;
var helpheight=(obj.height<maxSize)?obj.height:maxSize;
if (obj.width>obj.height){ //landscape
helpheight=helpwidth*obj.height/obj.width
} else { //portrait
helpwidth=helpheight*obj.width/obj.height
}
var component=Qt.createComponent("qrc:/qml/photoqml/PhotoPlaceholder.qml");
var sprite = component.createObject(fotostab, {"x":0,"y":0,"imageName":storagedirectory+"/"+obj.filename ,"width":helpwidth,"height":helpheight,"source": obj["link"]["4"],"downloadtype":"picture"});
callback(obj,sprite)
}
function deleteImageData(database,user,field,selection,callback) { // does nothing useful at the moment
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
print(' delete Image Data() for ' + field +"="+selection)
db.transaction( function(tx) {
result = tx.executeSql('UPDATE imageData SET data="" where '+ field +'="'+selection+'"');
callback(result)})
}
function requestFriendsAlbumPictures(friend,rootwindow,callback){
// screenscraping of albums page of contact without user and password
Helperjs.friendicaWebRequest(friend.url.replace("profile","photos"),rootwindow,function(photohtml){
var photoarray=[];
var arr = photohtml.split("sidebar-photos-albums-li");
for (var i=2;i<arr.length;i++){
var albumlink = arr[i].substring(arr[i].indexOf('http'),arr[i].indexOf('class')-2);
var albumname=arr[i].substring(arr[i].indexOf('/span')+6,arr[i].indexOf('</a>')-1);
var album={'link':albumlink,'name':albumname}
photoarray.push(album);
}
//print("Album"+JSON.stringify(photoarray));
callback(photoarray)
})
}
function requestFriendsPictures(link,rootwindow,callback){
// screenscraping of pictures page for given album
Helperjs.friendicaWebRequest(link,rootwindow,function(photohtml){
var photoarray=[];
var basehtml=photohtml.substring(photohtml.indexOf('<base')+12,photohtml.indexOf('/>',photohtml.indexOf('<base'))-2);
// old theme
if (photohtml.indexOf("photo-album-image-wrapper-end")>-1){ //theme 1
var arr = photohtml.split("photo-album-image-wrapper-end");}
// other themes
if (photohtml.indexOf("photo-album-wrapper")>-1){ //theme 2
var photoarea=photohtml.substring(photohtml.indexOf("photo-album-wrapper"),photohtml.indexOf("photo-album-end"))
var arr = photoarea.split("</a>");}
for (var i=0;i<arr.length-1;i++){
var photoname=arr[i].substring(arr[i].lastIndexOf('alt')+5,arr[i].lastIndexOf('title')-2);
var thumblink=arr[i].substring(arr[i].lastIndexOf('<img')+10,arr[i].lastIndexOf('alt')-2);
var imagetype=thumblink.substring(thumblink.lastIndexOf("."));
var photolink=thumblink.substring(0,thumblink.length-imagetype.length-2)+"-0"+imagetype
if(thumblink.substring(0,4)!=="http"){thumblink=basehtml+thumblink}
if(photolink.substring(0,4)!=="http"){photolink=basehtml+photolink}
var photo={'link':photolink,'name':photoname,'thumb':thumblink}
photoarray.push(photo);
}
callback(photoarray)
})
}
// 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) {
print('... create table')
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)');
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)');
tx.executeSql('CREATE TABLE IF NOT EXISTS contacts(username TEXT, id INT, name TEXT, screen_name TEXT, location TEXT,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)');
tx.executeSql('CREATE TABLE IF NOT EXISTS groups(username TEXT, groupname TEXT, gid INT, members TEXT)');
})}
function storeConfig(database,obj) { // stores config to DB
var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
print('storeConfig() for ' + obj.username)
print('database: ' + database[0]);
db.transaction( function(tx) {
print('... check if a object exists: '+obj.username)
var result = tx.executeSql('SELECT * from config WHERE username="'+obj.username+'"');
if(result.rows.length === 1) {// use update
print(obj.username +' exists, update it');
var result2 = tx.executeSql('UPDATE config SET server="'+obj.server+'",password="'+obj.password+'", imagestore="'+obj.imagestore+'", maxnews="+obj.maxnews+", isActive=0 WHERE username="'+obj.username +'"');
var result3 = tx.executeSql('UPDATE config SET isActive=1 WHERE username !="'+obj.username +'"');
var result4 = tx.executeSql('UPDATE config SET maxnews='+obj.maxnews);
} 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, obj.maxnews, 0,"list",0]);
var result3 = tx.executeSql('UPDATE config SET isActive=1 WHERE username !="'+obj.username +'"');
var result4 = tx.executeSql('UPDATE config SET maxnews='+obj.maxnews);
print("Inserted");}
});}
function getServerConfig(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+"'}";
callback(serverconfigString);
})}
catch (e){callback (e);
}}
function readConfig(database,callback,filter,filtervalue) { // reads config
print('readConfig()')
if (filter){var where = " WHERE "+ filter +" = '" + filtervalue+"'";} else { var where="";}
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 {
print('... read from database '+where)
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,maxnews:rsArray[0].maxnews,isActive:rsArray[0].isActive};
} else {
var rsObject=""
}
callback(rsObject);}}
);
}
function readActiveConfig(database){
var obj;
readConfig(database,function(config){
obj=config},"isActive", 0);
return obj;
}
function deleteConfig(database,userobj,callback) { // delete user data from DB
print('deleteConfig()')
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) {
print('... read from database '+where)
var rs = tx.executeSql('delete * from config'+where);
print(rs.toString);
callback(rs);
});
}