Code

important compile fix!
[ncmpc.git] / src / screen_lyrics.c
1 /* 
2  * $Id: screen_lyrics.c 3355 2006-09-1 17:44:04Z tradiaz $
3  *      
4  * (c) 2006 by Kalle Wallin <kaw@linux.se>
5  * Tue Aug  1 23:17:38 2006
6  * lyrics enhancement written by Andreas Obergrusberger <tradiaz@yahoo.de> 
7  * using www.leoslyrics.com XML API
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */
24 #include <stdlib.h>
25 #include <string.h>
26 #include <glib.h>
27 #include <ncurses.h>
28 #include <expat.h>
29 #include <unistd.h>
31 #include "config.h"
32 #ifndef DISABLE_LYRICS_SCREEN
33 #include <sys/stat.h>
34 #include "ncmpc.h"
35 #include "options.h"
36 #include "mpdclient.h"
37 #include "command.h"
38 #include "screen.h"
39 #include "screen_utils.h"
40 #include "easy_download.h"
41 #include "strfsong.h"
44 #define LEOSLYRICS_SEARCH_URL "http://api.leoslyrics.com/api_search.php?auth=ncmpc&artist=%s&songtitle=%s"
45  
46 #define LEOSLYRICS_CONTENT_URL "http://api.leoslyrics.com/api_lyrics.php?auth=ncmpc&hid=%s"
48 #define CREDITS "Lyrics provided by www.LeosLyrics.com"
49 typedef struct _formed_text
50 {
51         GString *text;
52         GArray *lines;
53         int val;
54 } formed_text;
56 typedef struct _retrieval_spec
57 {
58         mpdclient_t *client;
59         int way;
60 } retrieval_spec;
64 XML_Parser parser, contentp;
65 static int lyrics_text_rows = -1;
66 static list_window_t *lw = NULL;
67 guint8 result;
68 char *hid;
69 GTimer *dltime;
70 short int lock;
71 formed_text lyr_text;
72 /* result is a bitset in which the succes when searching 4 lyrics is logged
73 countend by position - backwards
74 0: lyrics in database
75 1: proper access  to the lyrics provider
76 2: lyrics found
77 3: exact match
78 4: lyrics downloaded
79 5: lyrics saved
80 wasting 3 bits doesn't mean being a fat memory hog like kde.... does it?
81 */
82 static void lyrics_paint(screen_t *screen, mpdclient_t *c);
84 int get_text_line(formed_text *text, int num, char *dest, int len)
85 {
86         memset(dest, '\0', len*sizeof(char));
87     if(num >= text->lines->len-1) return -1;    
88         int linelen;
89         if(num == 0)
90         {
91                 linelen = g_array_index(text->lines, int, num);
92                 memcpy(dest, text->text->str, linelen*sizeof(char));    
93         }
94         else if(num == 1)
95         { //dont ask me why, but this is needed....
96                 linelen = g_array_index(text->lines, int, num)
97                         - g_array_index(text->lines, int, num-1);
98                 memcpy(dest, &text->text->str[g_array_index(text->lines, int, num-1)],
99                 linelen*sizeof(char));  
100         }       
101         else
102         {
103                 linelen = g_array_index(text->lines, int, num+1)
104                         - g_array_index(text->lines, int, num);
105                 memcpy(dest, &text->text->str[g_array_index(text->lines, int, num)],
106                 linelen*sizeof(char));  
107         }
108         dest[linelen] = '\n';
109         dest[linelen+1] = '\0';
110         
111         return 0;
113         
114 void add_text_line(formed_text *dest, const char *src, int len)
116         // need this because g_array_append_val doesnt work with literals
117         // and expat sends "\n" as an extra line everytime
118         if(len == 0)
119         {
120                 dest->val = strlen(src);
121                 if(dest->lines->len > 0) dest->val += g_array_index(dest->lines, int,
122                                                                         dest->lines->len-1);
123                 g_string_append(dest->text, src);
124                 g_array_append_val(dest->lines, dest->val);
125                 return;
126         }
127         if(len > 1 || dest->val == 0) 
128         {
129                 dest->val = len;        
130                 if(dest->lines->len > 0) dest->val += g_array_index(dest->lines, int,
131                                                                         dest->lines->len-1);
132         }
133         else if (len == 1 && dest->val != 0) dest->val = 0;
134                                 
135         if(dest->val > 0)
136         { 
137                 g_string_append_len(dest->text, src, len);
138                 g_array_append_val(dest->lines, dest->val);
139         }
142 void formed_text_init(formed_text *text)
144         if(text->text != NULL) g_string_free(text->text, TRUE); 
145         text->text = g_string_new("");
146         
147         if(text->lines != NULL) g_array_free(text->lines, TRUE);
148         text->lines = g_array_new(FALSE, TRUE, 4);
149         
150         text->val = 0;
153 static void check_content(void *data, const char *name, const char **atts)
154
155         if(strstr(name, "text") != NULL)
156         {
158                 result |= 16;
159         }
161         
163 static void check_search_response(void *data, const char *name,
164                  const char **atts)
166         if(strstr(name, "response") != NULL)
167         {
168         result |=2;
169         return;
170         }  
171         
172         if(result & 4)
173         {
174                 if(strstr(name, "result") != NULL)
175                 {
176                         if(strstr(atts[2], "hid") != NULL)
177                         {
178                                 hid = atts[3];
179                         }
180         
181                         if(strstr(atts[2], "exactMatch") != NULL)
182                         {
183                                 result |= 8;
184                         }                       
185                 }
186         }
187                         
190 static void end_tag(void *data, const char *name)
192   //hmmmmmm             
195   static void check_search_success(void *userData, const XML_Char *s, int len)
196     {
197         if(result & 2)  //lets first check whether we're right
198         {               //we don't really want to search in the wrong string
199                 if(strstr((char*) s, "SUCCESS"))
200                 {
201                 result |=4;
202                 }
203         }       
204     }
206 static void fetch_text(void *userData, const XML_Char *s, int len) 
208         if(result & 16)
209         {
210                 add_text_line(&lyr_text, s, len); 
211         }
214 int check_dl_progress(void *clientp, double dltotal, double dlnow,
215                         double ultotal, double ulnow)
217         if(g_timer_elapsed(dltime, NULL) >= options.lyrics_timeout || lock == 4)
218         {       
219                 while (1)fprintf(stderr,"hihffo!");
220                 formed_text_init(&lyr_text);
221                 return -1;
222         }
224         return 0;
225 }       
228 int check_lyr_http(char *artist, char *title, char *url)
230         char url_avail[256];
232         //this replacess the whitespaces with '+'
233         g_strdelimit(artist, " ", '+');
234         g_strdelimit(title, " ", '+');
235         
236         //we insert the artist and the title into the url               
237         snprintf(url_avail, 512, LEOSLYRICS_SEARCH_URL, artist, title);
239         //download that xml!
240         easy_download_struct lyr_avail = {NULL, 0,-1};  
241         
242         g_timer_start(dltime);
243         if(!easy_download(url_avail, &lyr_avail, check_dl_progress)) return -1;
244         g_timer_stop(dltime);
246         //we gotta parse that stuff with expat
247         parser = XML_ParserCreate(NULL);
248     XML_SetUserData(parser, NULL);
249         
250         XML_SetElementHandler(parser, check_search_response, end_tag);
251         XML_SetCharacterDataHandler(parser, check_search_success);
252         XML_Parse(parser, lyr_avail.data, strlen(lyr_avail.data), 0);   
253         XML_ParserFree(parser); 
255         if(!(result & 4)) return -1; //check whether lyrics found
256         snprintf(url, 512, LEOSLYRICS_CONTENT_URL, hid);
258         return 0;
260 int get_lyr_http(char *artist, char *title)
262         char url_hid[256];
263         if(dltime == NULL) dltime = g_timer_new();
265         if(check_lyr_http(artist, title, url_hid) != 0) return -1;
266         
267         easy_download_struct lyr_content = {NULL, 0,-1};  
268         g_timer_continue(dltime);               
269         if(!(easy_download(url_hid, &lyr_content, check_dl_progress))) return -1;
270         g_timer_stop(dltime);
271         
272         contentp = XML_ParserCreate(NULL);
273         XML_SetUserData(contentp, NULL);
274         XML_SetElementHandler(contentp, check_content, end_tag);        
275         XML_SetCharacterDataHandler(contentp, fetch_text);
276         XML_Parse(contentp, lyr_content.data, strlen(lyr_content.data), 0);
277         XML_ParserFree(contentp);
279         return 0;
280         
282 FILE *create_lyr_file(char *artist, char *title)
284                 char path[1024];
286                 snprintf(path, 1024, "%s/.lyrics", 
287                         getenv("HOME"));
288                 if(g_access(path, W_OK) != 0) if(mkdir(path, S_IRWXU) != 0) return NULL;
289         
290                 snprintf(path, 1024, "%s/.lyrics/%s", 
291                                 getenv("HOME"), artist);
292                 if(g_access(path, W_OK) != 0) if(mkdir(path, S_IRWXU) != 0) return NULL;        
293         
294                 snprintf(path, 1024, "%s/.lyrics/%s/%s.lyric", 
295                                 getenv("HOME"), artist, title);
297         FILE *file = fopen(path, "w");
298 }       
300 char *check_lyr_hd(char *artist, char *title, int how)
301 { //checking whether for lyrics file existence and proper access
302         static char path[1024];
303         snprintf(path, 1024, "%s/.lyrics/%s/%s.lyric", 
304                         getenv("HOME"), artist, title);
305     
306     if(g_access(path, how) != 0) return NULL;
307                  
308         return path;
309 }               
312 int get_lyr_hd(char *artist, char *title)
314         char *path = check_lyr_hd(artist, title, R_OK);
315         if(path == NULL) return -1;
316         
317         FILE *lyr_file; 
318         lyr_file = fopen(path, "r");
319         if(lyr_file == NULL) return -1;
320         
321         char *buf = NULL;
322         char **line = &buf;
323         size_t n = 0;
324         
325         while(1)
326         {
327          n = getline(line, &n, lyr_file); 
328          if( n < 1 || *line == NULL || feof(lyr_file) != 0 ) return 0;
329          add_text_line(&lyr_text, *line, n+1);
330          free(*line);
331          *line = NULL; n = 0;
332         }
333         
334         return 0;
335 }       
336     
337 int store_lyr_hd()
339         char artist[512];
340         char title[512];
341         static char path[1024];
342         FILE *lyr_file;
343         
344         get_text_line(&lyr_text, 0, artist, 512);
345         get_text_line(&lyr_text, 1, title, 512);
346         artist[strlen(artist)-1] = '\0';
347         title[strlen(title)-1] = '\0';
348         
349         snprintf(path, 1024, "%s/.lyrics/%s/%s.lyric", 
350                         getenv("HOME"), artist, title);
351         lyr_file = create_lyr_file(artist, title);
352         if(lyr_file == NULL) return -1;
353         int i;
354         char line_buf[1024];
355         
356         for(i = 4; i <= lyr_text.text->len; i++)
357         {
358                 if(get_text_line(&lyr_text, i, line_buf, 1024) == -1);
359                 fputs(line_buf, lyr_file);
360         }
361         fclose(lyr_file);
362         return 0;
364                                 
365         
366 void check_repaint()
368         if(screen_get_id("lyrics") == get_cur_mode_id())lyrics_paint(NULL, NULL);
372 gpointer get_lyr(void *c)
374         mpd_Status *status = ((retrieval_spec*)c)->client->status;
375         mpd_Song *cur = ((retrieval_spec*)c)->client->song; 
376         //mpdclient_update((mpdclient_t*)c);
377         
378         if(!(IS_PAUSED(status->state)||IS_PLAYING(status->state)))
379         {
380                 formed_text_init(&lyr_text);                    
381                 return NULL;
382         }
383         
385         char artist[MAX_SONGNAME_LENGTH];
386         char title[MAX_SONGNAME_LENGTH];
387         lock = 2;
388         result = 0;
389         
390         formed_text_init(&lyr_text);
391         
392         strfsong(artist, MAX_SONGNAME_LENGTH, "%artist%", cur);
393         strfsong(title, MAX_SONGNAME_LENGTH, "%title%", cur);
394         
395         //write header..
396         formed_text_init(&lyr_text);
397         add_text_line(&lyr_text, artist, 0);
398         add_text_line(&lyr_text, title, 0);
399         add_text_line(&lyr_text, "", 0);
400         add_text_line(&lyr_text, "", 0);
401         
402         if (((retrieval_spec*)c)->way == 1)
403         {
404                  if(get_lyr_http(artist, title) != 0) return NULL;
405         }
406         else{
407                 if(get_lyr_hd(artist, title) != 0) 
408                 {
409                 if(get_lyr_http(artist, title) != 0) return NULL;
410                 }
411                 else result |= 1;
412         }
413         
414         lw->start = 0;
415         check_repaint();
416         lock = 1;
417         return &lyr_text;
418 }       
420 static char *
421 list_callback(int index, int *highlight, void *data)
423         static char buf[512];
424         
425     //i think i'ts fine to write it into the 1st line...
426   if((index == lyr_text.lines->len && lyr_text.lines->len > 4)||
427           ((lyr_text.lines->len == 0 
428           ||lyr_text.lines->len == 4) && index == 0))
429   {
430     *highlight=3; 
431         return CREDITS;
432   }
433     
434   if(index < 2 && lyr_text.lines->len > 4) *highlight=3;
435   else if(index >=  lyr_text.lines->len ||
436         ( index < 4 && index != 0 && lyr_text.lines->len < 5))
437   {
438           return "";
439   }
440  
441   get_text_line(&lyr_text, index, buf, 512);
442   return buf;
443
446 static void
447 lyrics_init(WINDOW *w, int cols, int rows)
449   lw = list_window_init(w, cols, rows);
450   lw->flags = LW_HIDE_CURSOR;
451   //lyr_text.lines = g_array_new(FALSE, TRUE, 4);
452   formed_text_init(&lyr_text);
453   if (!g_thread_supported()) g_thread_init(NULL);
454   
457 static void
458 lyrics_resize(int cols, int rows)
460   lw->cols = cols;
461   lw->rows = rows;
464 static void
465 lyrics_exit(void)
467   list_window_free(lw);
471 static char *
472 lyrics_title(char *str, size_t size)
474         if(lyr_text.lines->len == 4)
475         {
476                 if(lock == 1)
477                 {
478                         if(!(result & 1))
479                         {
480                                 if(!(result & 2)) return _("Lyrics  [No connection]");
481                                 if(!(result & 4)) return _("Lyrics  [Not found]"); 
482                         }
483                 }
484                 if(lock == 2) return _("Lyrics  [retrieving]");
485         }
486         /*if(lyr_text.lines->len > 2) 
487         {
488                 static char buf[512];
489                 char artist[512];
490                 char title[512];
491                 get_text_line(&lyr_text, 0, artist, 512);
492                 get_text_line(&lyr_text, 1, artist, 512);
493                 snprintf(buf, 512, "Lyrics  %s - %s", artist, title);
494                 return buf;
495         }*/
496         return "Lyrics";
499 static void 
500 lyrics_paint(screen_t *screen, mpdclient_t *c)
502   lw->clear = 1;
503   list_window_paint(lw, list_callback, NULL);
504   wrefresh(lw->w);
507 static void 
508 lyrics_update(screen_t *screen, mpdclient_t *c)
509 {  
510   if( lw->repaint )
511     {
512       list_window_paint(lw, list_callback, NULL);
513       wrefresh(lw->w);
514       lw->repaint = 0;
515     }
519 static int 
520 lyrics_cmd(screen_t *screen, mpdclient_t *c, command_t cmd)
522   lw->repaint=1;
523   static retrieval_spec spec;
524   char *msg;
525   switch(cmd)
526     {
527     case CMD_LIST_NEXT:
528       if( lw->start+lw->rows < lyr_text.lines->len+1 )
529         lw->start++;
530       return 1;
531     case CMD_LIST_PREVIOUS:
532       if( lw->start >0 )
533         lw->start--;
534       return 1;
535     case CMD_LIST_FIRST:
536       lw->start = 0;
537       return 1;
538     case CMD_LIST_LAST:
539       lw->start = lyrics_text_rows-lw->rows;
540       if( lw->start<0 )
541         lw->start = 0;
542       return 1;
543     case CMD_LIST_NEXT_PAGE:
544       lw->start = lw->start + lw->rows-1;
545       if( lw->start+lw->rows >= lyr_text.lines->len+1 )
546         lw->start = lyr_text.lines->len-lw->rows+1;
547       if( lw->start<0 )
548         lw->start = 0;
549        return 1;
550     case CMD_LIST_PREVIOUS_PAGE:
551       lw->start = lw->start - lw->rows;
552       if( lw->start<0 )
553         lw->start = 0;
554       return 1;
555         case CMD_SELECT:
556           spec.client = c;
557           spec.way = 0;
558           g_thread_create(get_lyr, &spec, FALSE, NULL); 
559           return 1;
560         case CMD_INTERRUPT:
561           if(lock > 1) lock = 4;
562           return 1;     
563         case CMD_ADD:
564           if(lock > 0 && lock != 4)
565           {
566                  if(store_lyr_hd() == 0) screen_status_message (_("Lyrics saved!"));
567           }
568           return 1;
569         case CMD_LYRICS_UPDATE:
570           spec.client = c;
571           spec.way = 1;
572           g_thread_create(get_lyr, &spec, FALSE, NULL);
573         default:
574       break;
575     }
577   lw->selected = lw->start+lw->rows;
578   if( screen_find(screen, c, 
579                   lw,  lyrics_text_rows,
580                   cmd, list_callback, NULL) )
581     {
582       /* center the row */
583       lw->start = lw->selected-(lw->rows/2);
584       if( lw->start+lw->rows > lyrics_text_rows )
585         lw->start = lyrics_text_rows-lw->rows;
586       if( lw->start<0 )
587         lw->start=0;
588       return 1;
589     }
591   return 0;
594 static list_window_t *
595 lyrics_lw(void)
597   return lw;
600 screen_functions_t *
601 get_screen_lyrics(void)
603   static screen_functions_t functions;
605   memset(&functions, 0, sizeof(screen_functions_t));
606   functions.init   = lyrics_init;
607   functions.exit   = lyrics_exit;
608   functions.open   = NULL;
609   functions.close  = NULL;
610   functions.resize = lyrics_resize;
611   functions.paint  = lyrics_paint;
612   functions.update = lyrics_update;
613   functions.cmd    = lyrics_cmd;
614   functions.get_lw = lyrics_lw;
615   functions.get_title = lyrics_title;
617   return &functions;
619 #endif /* ENABLE_LYRICS_SCREEN */