-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.c
661 lines (563 loc) · 15.6 KB
/
util.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
/*
* Copyright (C) 2009-2016 Christian Heckendorf <[email protected]>
*
* 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.
*
* 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/>.
*/
#include "util.h"
#include "defs.h"
#include "dbact.h"
#include "plugins/plugin.h"
int experr(const char *epath, int eerrno){
fprintf(stderr,"error: %d on %s\n",eerrno,epath);
return 0;
}
int isURL(const char *in){
return strncmp("http://",in,7)==0;
}
char *expand(char *in, const int size){
char *tmp;
char *in_ptr=in;
char *tmp_ptr;
int url=0,x;
tmp_ptr=tmp=malloc(size);
if(tmp==NULL)
return NULL;
if(isURL(in))url=1; /* Clean \n but do no globbing */
for(x=0;x<size-1 && in[x];x++);
if(x>0 && in[x-1]=='\n')
in[x-1]=0;
if(x>1 && in[x-2]=='\r')
in[x-2]=0;
in[x]=0;
if(url)return in;
if(in[0]=='~'){
strlcpy(tmp,getenv("HOME"),size);
strlcat(tmp,"/",size);
strlcat(tmp,in+2,size);
strlcpy(in,tmp,size);
}
else if(in[0]!='/'){
getcwd(tmp,size);
strlcat(tmp,"/",size);
if(in[0]=='.' && in[1]=='/')
strlcat(tmp,in+2,size);
else
strlcat(tmp,in,size);
strlcpy(in,tmp,size);
}
while(*in_ptr){
if(*in_ptr=='[' || *in_ptr=='\'' || *in_ptr=='\"')
*(tmp_ptr++)='\\';
*(tmp_ptr++)=*(in_ptr++);
}
*tmp_ptr=0;
glob_t pglob;
glob(tmp,GLOB_TILDE,&experr,&pglob);
if(pglob.gl_pathc>0){
memmove(tmp,pglob.gl_pathv[0],100);
debug(1,"Glob OK!");
}
else
debug(1,"No files match");
globfree(&pglob);
free(tmp);
return in;
}
int fileFormat(struct pluginitem **list, const char *arg){
FILE *ffd=NULL;
struct pluginitem **ret=list;
int type=PLUGIN_NULL;
int x=0;
int i,j;
// Find by magic numbers
for(i=0;type==PLUGIN_NULL && i<PLUGIN_NULL;i++){
if(ret[i]==NULL)
continue;
if((ffd=ret[i]->modopen(arg,"rb"))!=NULL){
if(ret[i]->moddata(ffd)){
type=i;
}
ret[i]->modclose(ffd);
}
}
if(ffd==NULL)
type=PLUGIN_NULL;
if(type!=PLUGIN_NULL){
return type;
}
// Find by extension
for(x=0;arg[x];x++);
for(;arg[x-1]!='.' && x>0;x--);
for(i=0;i<PLUGIN_NULL;i++){
if(ret[i]==NULL)
continue;
for(j=0;ret[i]->extension[j];j++)
if(strcasecmp(arg+x,ret[i]->extension[j])==0)
return i;
}
return PLUGIN_NULL;
}
#if 0
int getFileTypeByName(const char *name){
char query[200];
int type=0;
if(!name)return 0;
sprintf(query,"SELECT TypeID FROM FileType WHERE Name='%s' LIMIT 1",name);
harp_sqlite3_exec(conn,query,uint_return_cb,&type,NULL);
return type;
}
int findPluginIDByType(int type){
static int last_type=0;
static int index=0;
unsigned int id=0;
char query[150];
if(type==0 || (type!=last_type && last_type!=0)){
last_type=index=0;
if(type==0)return 0;
}
last_type=type;
sprintf(query,"SELECT PluginID FROM PluginType WHERE TypeID=%d LIMIT %d,1",type,index);
harp_sqlite3_exec(conn,query,uint_return_cb,&id,NULL);
index++;
return id;
}
struct pluginitem *findPluginByID(struct pluginitem *list, int id){
while(list && list->id!=id)
list=list->next;
return list;
}
int getPluginModule(void **module, char *lib){
char library[250];
sprintf(library,"%s/%s",LIB_PATH,lib);
debug(2,library);
dlerror();
*module=dlopen(library,RTLD_LAZY);
if(!*module){
fprintf(stderr,"Can't open plugin.\n\t%s\n",dlerror());
return 2;
}
else{
dlerror();
}
return 1;
}
int getPlugin(struct dbitem *dbi, const int index, void **module){
if(!fetch_row(dbi)){
if(dbi->current_row==dbi->column_count || dbi->row_count==0)
fprintf(stderr,"No plugins found.\n\tSee README for information about installing plugins.\n");
return 0;
}
return getPluginModule(module,dbi->row[index]);
}
struct pluginitem *closePlugin(struct pluginitem *head){
struct pluginitem *ptr=head;
if(!head)return NULL;
ptr=ptr->next;
if(head->module)
dlclose(head->module);
free(head);
return ptr;
}
void closePluginList(struct pluginitem *head){
struct pluginitem *ptr=head;
do{
ptr=closePlugin(ptr);
}while(ptr);
}
static int regPluginFunctions(struct pluginitem *node){
if(!node->module)return 1;
if(!(node->modopen=dlsym(node->module,"plugin_open")) ||
!(node->moddata=dlsym(node->module,"filetype_by_data")) ||
!(node->modmeta=dlsym(node->module,"plugin_meta")) ||
!(node->modplay=dlsym(node->module,"plugin_run")) ||
!(node->modseek=dlsym(node->module,"plugin_seek")) ||
!(node->modclose=dlsym(node->module,"plugin_close")))
return 1;
return 0;
}
static int open_plugin_cb(void *arg, int col_count, char **row, char **titles){
struct pluginitem **node = (struct pluginitem**)arg;
struct pluginitem *next;
if(!(next=malloc(sizeof(struct pluginitem)))){
debug(2,"Malloc failed (open_plugin_cb).");
return 1;
}
if(getPluginModule(&(next->module),row[1])!=1){
free(next);
return 1;
}
else{
if(regPluginFunctions(next)){
gree(nexu);
return 1;
}
else{
(*node)->next=next;
*node=next;
next->next=NULL;
next->id=strtol(row[0],NULL,10);
next->contenttype=strdup(row[2]);
}
}
return 0;
}
struct pluginitem **openPlugins(){
struct pluginitem prehead,*ptr;
return plugin_head;
prehead.next=NULL;
ptr=&prehead;
// Add order by active?
if(harp_sqlite3_exec(conn,"SELECT Plugin.PluginID,Plugin.Library,FileType.ContentType FROM Plugin NATURAL JOIN PluginType NATURAL JOIN FileType",open_plugin_cb,&ptr,NULL)!=SQLITE_OK){
closePluginList(prehead.next);
fprintf(stderr,"Error opening plugins.\n");
return NULL;
}
//return prehead.next; /* List starts at this next */
}
#endif
char *getFilename(const char *path){
char *filestart=(char *)path;
while(*path){
if(*(path++)=='/')
filestart=(char *)path;
}
return filestart;
}
static void printIDMatchRow(struct dbitem *dbi){
int x;
printf("%s\t%s",dbi->row[0],dbi->row[1]);
if(dbi->column_count>2){
printf("\t(%s",dbi->row[2]);
for(x=3;x<dbi->column_count;x++)
printf(": %s",dbi->row[x]);
printf(")");
}
printf("\n");
}
int getBestIDMatch(struct dbitem *dbi, const char *argv){
int id=0,found=0;
if(!dbi)return 0;
printf("Total matches for string '%s': %d\n",argv,dbi->row_count);
while(fetch_row(dbi)){
printIDMatchRow(dbi);
if(!strcmp(argv,dbi->row[1])){ // Perfect matches take priority
id=(int)strtol(dbi->row[0],NULL,10);
if(id)found++;
}
else if(!strcasecmp(argv,dbi->row[1])){ // Case-insensitive matches can be used
id=(int)strtol(dbi->row[0],NULL,10); // Continue to look for perfect matches
}
}
if(id && found==1)
printf("Using best match: %d\n",id);
else{
char choice[100];
printf("Please choose an ID: ");
if(!fgets(choice,sizeof(choice),stdin))
id=0;
else
id=(int)strtol(choice,NULL,10);
}
return id;
}
int strToID(const char *argv){ // TODO: add type param
char query[351];
char clean_str[200];
int id=0;
struct dbitem dbi;
db_safe(clean_str,argv,200);
if(!arglist[ATYPE].subarg)return -1;
dbiInit(&dbi);
switch(arglist[ATYPE].subarg[0]){
case 's':snprintf(query,351,"SELECT SongID,SongTitle,ArtistName,AlbumTitle FROM SongPubInfo WHERE SongTitle LIKE '%%%s%%'",clean_str);break;
case 'p':snprintf(query,351,"SELECT PlaylistID,Title FROM Playlist WHERE Title LIKE '%%%s%%'",clean_str);break;
case 'r':snprintf(query,351,"SELECT ArtistID,Name FROM Artist WHERE Name LIKE '%%%s%%'",clean_str);break;
case 'a':snprintf(query,351,"SELECT AlbumID,Title,Artist.Name FROM Album NATURAL JOIN AlbumArtist NATURAL JOIN Artist WHERE Title LIKE '%%%s%%'",clean_str);break;
case 'g':snprintf(query,351,"SELECT CategoryID,Name FROM Category WHERE Name LIKE '%%%s%%'",clean_str);break;
case 't':snprintf(query,351,"SELECT TagID,Value FROM Tag WHERE Value LIKE '%%%s%%'",clean_str);break;
default:return -1;
}
if(doQuery(query,&dbi)==1 && fetch_row(&dbi)){
id=(int)strtol(dbi.row[0],NULL,10);
}
else if(dbi.row_count>1)
id=getBestIDMatch(&dbi,argv);
dbiClean(&dbi);
return id;
}
int verifyID(const int id){
char query[100];
struct dbitem dbi;
dbiInit(&dbi);
switch(arglist[ATYPE].subarg[0]){
case 's':snprintf(query,100,"SELECT SongID FROM Song WHERE SongID=%d",id);break;
case 'p':snprintf(query,100,"SELECT PlaylistID FROM Playlist WHERE PlaylistID=%d",id);break;
case 'r':snprintf(query,100,"SELECT ArtistID FROM Artist WHERE ArtistID=%d",id);break;
case 'a':snprintf(query,100,"SELECT AlbumID FROM Album WHERE AlbumID=%d",id);break;
case 'g':snprintf(query,100,"SELECT CategoryID FROM Category WHERE CategoryID=%d",id);break;
case 't':snprintf(query,100,"SELECT TagID FROM Tag WHERE TagID=%d",id);break;
default:return 0;
}
if(doQuery(query,&dbi)==1){
dbiClean(&dbi);
return 1;
}
dbiClean(&dbi);
return 0;
}
int getID(const char *arg){
int id;
char *endptr;
if(arg==NULL){
printf("Required argument not provided\n");
return -1;
}
id=(int)strtol(arg,&endptr,10);
if(*endptr!=0){
if((id=strToID(arg))<1 ){
debug(1,"No ID found from given name.");
return -1;
}
}
if(!verifyID(id)){
debug(1,"No ID found.");
return -1;
}
return id;
}
int *getMulti(char *arg, int *length){
const char del[]=",";
char *token;
int *list,*ptr;
*length=1;
token=arg;
while(*token){
if(*(token++)==',')
(*length)++;
}
if(!(ptr=list=malloc(sizeof(int)*(*length)))){
debug(2,"Malloc failed (list).");
return NULL;
}
while((token=strsep(&arg,del))){
if(!((*ptr=(int)strtol(token,NULL,10))>0 && verifyID(*ptr))){
if(!(*ptr=strToID(token))){
continue;
}
}
ptr++;
}
if(ptr==list)*list=-1;
return list;
}
int getGroupSongIDs(char *args, const int arglen, struct IDList *id_struct){
int y,x=0;
int *song_ids=malloc(sizeof(int));
int *group_ids=malloc(sizeof(int));
int song_idlen;
int group_idlen;
char query[200],query_tail[100],*ptr;
char temp=0;
struct dbitem dbi;
dbiInit(&dbi);
query_tail[0]=0;
/* Default should be hit. Avoid selecting another option. */
if(args[x+1]!=' '){
temp=args[x];
args[x]=' ';
}
switch(args[x]){
case 'a':
arglist[ATYPE].subarg[0]='a';
snprintf(query,200,"SELECT SongID FROM Song INNER JOIN Album ON Album.AlbumID=Song.AlbumID WHERE Album.AlbumID=");
snprintf(query_tail,100,"ORDER BY Track");
ptr=&query[91];
break;
case 'r':
arglist[ATYPE].subarg[0]='r';
snprintf(query,200,"SELECT SongID FROM Song NATURAL JOIN AlbumArtist WHERE ArtistID=");
snprintf(query_tail,100,"ORDER BY Song.AlbumID,Track");
ptr=&query[64];
break;
case 't':
arglist[ATYPE].subarg[0]='t';
snprintf(query,200,"SELECT Song.SongID FROM Song NATURAL JOIN SongTag WHERE TagID=");
snprintf(query_tail,100,"ORDER BY Song.AlbumID,Track");
ptr=&query[62];
break;
case 'g':
arglist[ATYPE].subarg[0]='g';
snprintf(query,200,"SELECT SongID FROM Song NATURAL JOIN SongCategory WHERE CategoryID=");
snprintf(query_tail,100,"ORDER BY Song.AlbumID,Track");
ptr=&query[67];
break;
case 's':
x++;
default:
if(temp)args[x]=temp;
// List of SongIDs.
for(;x<arglen && args[x] && args[x]==' ';x++);
arglist[ATYPE].subarg[0]='s';
if(!args[x] || !(song_ids=getMulti(&args[x],&song_idlen)) || song_ids[0]<1)
return HARP_RET_ERR;
id_struct->tempselectid=insertTempSelect(song_ids,song_idlen);
id_struct->songid=song_ids;
id_struct->length=song_idlen;
return HARP_RET_OK;
}
debug(3,query);
// Get SongIDs from album, artist, or genre
for(++x;x<arglen && args[x] && args[x]==' ';x++);
if(!(group_ids=getMulti(&args[x],&group_idlen)))return HARP_RET_ERR;
if(group_ids[0]<1){
fprintf(stderr,"No results found.\n");
free(group_ids);
return HARP_RET_ERR;
}
for(song_idlen=x=0;x<group_idlen;x++){
snprintf(ptr,200-(ptr-query),"%d %s",group_ids[x],query_tail);
if(doQuery(query,&dbi)<1)continue;
y=song_idlen;
song_idlen+=dbi.row_count;
if(!(song_ids=realloc(song_ids,sizeof(int)*(song_idlen)))){
debug(2,"Realloc failed (song_ids).");
dbiClean(&dbi);
free(group_ids);
return HARP_RET_ERR;
}
for(;fetch_row(&dbi);y++)
song_ids[y]=(int)strtol(dbi.row[0],NULL,10);
}
dbiClean(&dbi);
free(group_ids); // Done with groups. We have the SongIDs.
if(!song_idlen){
fprintf(stderr,"No results found.\n");
free(song_ids);
return HARP_RET_ERR;
}
id_struct->tempselectid=insertTempSelect(song_ids,song_idlen);
id_struct->songid=song_ids;
id_struct->length=song_idlen;
return HARP_RET_OK;
}
void cleanTempSelect(const int tempid){
char query[100];
snprintf(query,100,"DELETE FROM TempSelect WHERE TempID=%d",tempid);
harp_sqlite3_exec(conn,query,NULL,NULL,NULL);
}
static void createTempSelect(){
harp_sqlite3_exec(conn,"CREATE TEMP TABLE IF NOT EXISTS TempSelect(TempSelectID integer not null primary key, TempID integer not null, SelectID integer not null)",NULL,NULL,NULL);
}
static int getNextTempSelectID(){
int tempid=0;
/* Replace with MAX(TempID)? */
if(harp_sqlite3_exec(conn,"SELECT TempID FROM TempSelect ORDER BY TempID DESC LIMIT 1",uint_return_cb,&tempid,NULL)==SQLITE_DONE)
return 1;
return ++tempid;
}
int mergeTempSelect(int ida, int idb){
char query[150];
if(ida==idb)
return ida;
snprintf(query,150,"UPDATE TempSelect SET TempID=%d where TempID=%d",ida,idb);
harp_sqlite3_exec(conn,query,NULL,NULL,NULL);
return ida;
}
int insertTempSelect(const int *ids, const int idlen){
unsigned int x,currentlimit,tempid;
struct dbitem dbi;
dbiInit(&dbi);
char query[150];
createTempSelect();
tempid=getNextTempSelectID();
x=currentlimit=0;
while(x<idlen){
if((currentlimit+=DB_BATCH_SIZE)>idlen)currentlimit=idlen;
harp_sqlite3_exec(conn,"BEGIN",NULL,NULL,NULL);
for(;x<currentlimit;x++){
snprintf(query,150,"INSERT INTO TempSelect(TempID,SelectID) VALUES(%d,%d)",tempid,ids[x]);
harp_sqlite3_exec(conn,query,NULL,NULL,NULL);
}
harp_sqlite3_exec(conn,"COMMIT",NULL,NULL,NULL);
}
return tempid;
}
int insertTempSelectQuery(const char *query){
const char *ins_q="INSERT INTO TempSelect(TempID,SelectID) ";
unsigned int tempid;
char *temp_q,*ptr;
const int qsize=strlen(ins_q)+strlen(query)+1;
if(!(temp_q=malloc(qsize))){
debug(2,"Malloc failed (tempquery)");
exit(1);
}
createTempSelect();
tempid=getNextTempSelectID();
snprintf(temp_q,qsize,query,tempid);
ptr=strdup(temp_q);
snprintf(temp_q,qsize,"%s%s",ins_q,ptr);
debug(2,temp_q);
harp_sqlite3_exec(conn,temp_q,NULL,NULL,NULL);
free(temp_q);
free(ptr);
return tempid;
}
int insertTempSelectQueryCount(const char *query,int *count){
int ret=insertTempSelectQuery(query);
*count=sqlite3_changes(conn);
return ret;
}
void miClean(struct musicInfo *mi){
memset(mi->title,0,MI_TITLE_SIZE);
memset(mi->album,0,MI_ALBUM_SIZE);
memset(mi->artist,0,MI_ARTIST_SIZE);
memset(mi->year,0,MI_YEAR_SIZE);
memset(mi->track,0,MI_TRACK_SIZE);
mi->length=insertconf.length;
}
void miFree(struct musicInfo *mi){
if(mi->title!=NULL)
free(mi->title);
if(mi->album!=NULL)
free(mi->album);
if(mi->artist!=NULL)
free(mi->artist);
if(mi->year!=NULL)
free(mi->year);
if(mi->track!=NULL)
free(mi->track);
}
void db_clean(char *str, const char *data, const size_t size){
int x;
for(x=0;*(data+x)==' ' && x<size;x++); // Strip starting spaces
while(*data && x++<size){ // Strip multi space
if(*data==' ' && *(data+1)==' '){
data++;
continue;
}
*(str++)=*(data++);
}
if(x>0 && *(str-1)==' ')str--; // Remove trailing space
*str=0;
}
void db_safe(char *str, const char *data, const size_t size){
int x=0;
while(*data && x++<size){ // Escape single quotes
if(*data=='\''){
*(str++)='\'';
}
*(str++)=*(data++);
}
*str=0;
}