Code

delte debug msg
[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                 formed_text_init(&lyr_text);
220                 return -1;
221         }
223         return 0;
224 }       
227 int check_lyr_http(char *artist, char *title, char *url)
229         char url_avail[256];
231         //this replacess the whitespaces with '+'
232         g_strdelimit(artist, " ", '+');
233         g_strdelimit(title, " ", '+');
234         
235         //we insert the artist and the title into the url               
236         snprintf(url_avail, 512, LEOSLYRICS_SEARCH_URL, artist, title);
238         //download that xml!
239         easy_download_struct lyr_avail = {NULL, 0,-1};  
240         
241         g_timer_start(dltime);
242         if(!easy_download(url_avail, &lyr_avail, check_dl_progress)) return -1;
243         g_timer_stop(dltime);
245         //we gotta parse that stuff with expat
246         parser = XML_ParserCreate(NULL);
247     XML_SetUserData(parser, NULL);
248         
249         XML_SetElementHandler(parser, check_search_response, end_tag);
250         XML_SetCharacterDataHandler(parser, check_search_success);
251         XML_Parse(parser, lyr_avail.data, strlen(lyr_avail.data), 0);   
252         XML_ParserFree(parser); 
254         if(!(result & 4)) return -1; //check whether lyrics found
255         snprintf(url, 512, LEOSLYRICS_CONTENT_URL, hid);
257         return 0;
259 int get_lyr_http(char *artist, char *title)
261         char url_hid[256];
262         if(dltime == NULL) dltime = g_timer_new();
264         if(check_lyr_http(artist, title, url_hid) != 0) return -1;
265         
266         easy_download_struct lyr_content = {NULL, 0,-1};  
267         g_timer_continue(dltime);               
268         if(!(easy_download(url_hid, &lyr_content, check_dl_progress))) return -1;
269         g_timer_stop(dltime);
270         
271         contentp = XML_ParserCreate(NULL);
272         XML_SetUserData(contentp, NULL);
273         XML_SetElementHandler(contentp, check_content, end_tag);        
274         XML_SetCharacterDataHandler(contentp, fetch_text);
275         XML_Parse(contentp, lyr_content.data, strlen(lyr_content.data), 0);
276         XML_ParserFree(contentp);
278         return 0;
279         
281 FILE *create_lyr_file(char *artist, char *title)
283                 char path[1024];
285                 snprintf(path, 1024, "%s/.lyrics", 
286                         getenv("HOME"));
287                 if(g_access(path, W_OK) != 0) if(mkdir(path, S_IRWXU) != 0) return NULL;
288         
289                 snprintf(path, 1024, "%s/.lyrics/%s", 
290                                 getenv("HOME"), artist);
291                 if(g_access(path, W_OK) != 0) if(mkdir(path, S_IRWXU) != 0) return NULL;        
292         
293                 snprintf(path, 1024, "%s/.lyrics/%s/%s.lyric", 
294                                 getenv("HOME"), artist, title);
296         FILE *file = fopen(path, "w");
297 }       
299 char *check_lyr_hd(char *artist, char *title, int how)
300 { //checking whether for lyrics file existence and proper access
301         static char path[1024];
302         snprintf(path, 1024, "%s/.lyrics/%s/%s.lyric", 
303                         getenv("HOME"), artist, title);
304     
305     if(g_access(path, how) != 0) return NULL;
306                  
307         return path;
308 }               
311 int get_lyr_hd(char *artist, char *title)
313         char *path = check_lyr_hd(artist, title, R_OK);
314         if(path == NULL) return -1;
315         
316         FILE *lyr_file; 
317         lyr_file = fopen(path, "r");
318         if(lyr_file == NULL) return -1;
319         
320         char *buf = NULL;
321         char **line = &buf;
322         size_t n = 0;
323         
324         while(1)
325         {
326          n = getline(line, &n, lyr_file); 
327          if( n < 1 || *line == NULL || feof(lyr_file) != 0 ) return 0;
328          add_text_line(&lyr_text, *line, n+1);
329          free(*line);
330          *line = NULL; n = 0;
331         }
332         
333         return 0;
334 }       
335     
336 int store_lyr_hd()
338         char artist[512];
339         char title[512];
340         static char path[1024];
341         FILE *lyr_file;
342         
343         get_text_line(&lyr_text, 0, artist, 512);
344         get_text_line(&lyr_text, 1, title, 512);
345         artist[strlen(artist)-1] = '\0';
346         title[strlen(title)-1] = '\0';
347         
348         snprintf(path, 1024, "%s/.lyrics/%s/%s.lyric", 
349                         getenv("HOME"), artist, title);
350         lyr_file = create_lyr_file(artist, title);
351         if(lyr_file == NULL) return -1;
352         int i;
353         char line_buf[1024];
354         
355         for(i = 4; i <= lyr_text.text->len; i++)
356         {
357                 if(get_text_line(&lyr_text, i, line_buf, 1024) == -1);
358                 fputs(line_buf, lyr_file);
359         }
360         fclose(lyr_file);
361         return 0;
363                                 
364         
365 void check_repaint()
367         if(screen_get_id("lyrics") == get_cur_mode_id())lyrics_paint(NULL, NULL);
371 gpointer get_lyr(void *c)
373         mpd_Status *status = ((retrieval_spec*)c)->client->status;
374         mpd_Song *cur = ((retrieval_spec*)c)->client->song; 
375         //mpdclient_update((mpdclient_t*)c);
376         
377         if(!(IS_PAUSED(status->state)||IS_PLAYING(status->state)))
378         {
379                 formed_text_init(&lyr_text);                    
380                 return NULL;
381         }
382         
384         char artist[MAX_SONGNAME_LENGTH];
385         char title[MAX_SONGNAME_LENGTH];
386         lock = 2;
387         result = 0;
388         
389         formed_text_init(&lyr_text);
390         
391         strfsong(artist, MAX_SONGNAME_LENGTH, "%artist%", cur);
392         strfsong(title, MAX_SONGNAME_LENGTH, "%title%", cur);
393         
394         //write header..
395         formed_text_init(&lyr_text);
396         add_text_line(&lyr_text, artist, 0);
397         add_text_line(&lyr_text, title, 0);
398         add_text_line(&lyr_text, "", 0);
399         add_text_line(&lyr_text, "", 0);
400         
401         if (((retrieval_spec*)c)->way == 1)
402         {
403                  if(get_lyr_http(artist, title) != 0) return NULL;
404         }
405         else{
406                 if(get_lyr_hd(artist, title) != 0) 
407                 {
408                 if(get_lyr_http(artist, title) != 0) return NULL;
409                 }
410                 else result |= 1;
411         }
412         
413         lw->start = 0;
414         check_repaint();
415         lock = 1;
416         return &lyr_text;
417 }       
419 static char *
420 list_callback(int index, int *highlight, void *data)
422         static char buf[512];
423         
424     //i think i'ts fine to write it into the 1st line...
425   if((index == lyr_text.lines->len && lyr_text.lines->len > 4)||
426           ((lyr_text.lines->len == 0 
427           ||lyr_text.lines->len == 4) && index == 0))
428   {
429     *highlight=3; 
430         return CREDITS;
431   }
432     
433   if(index < 2 && lyr_text.lines->len > 4) *highlight=3;
434   else if(index >=  lyr_text.lines->len ||
435         ( index < 4 && index != 0 && lyr_text.lines->len < 5))
436   {
437           return "";
438   }
439  
440   get_text_line(&lyr_text, index, buf, 512);
441   return buf;
442
445 static void
446 lyrics_init(WINDOW *w, int cols, int rows)
448   lw = list_window_init(w, cols, rows);
449   lw->flags = LW_HIDE_CURSOR;
450   //lyr_text.lines = g_array_new(FALSE, TRUE, 4);
451   formed_text_init(&lyr_text);
452   if (!g_thread_supported()) g_thread_init(NULL);
453   
456 static void
457 lyrics_resize(int cols, int rows)
459   lw->cols = cols;
460   lw->rows = rows;
463 static void
464 lyrics_exit(void)
466   list_window_free(lw);
470 static char *
471 lyrics_title(char *str, size_t size)
473         if(lyr_text.lines->len == 4)
474         {
475                 if(lock == 1)
476                 {
477                         if(!(result & 1))
478                         {
479                                 if(!(result & 2)) return _("Lyrics  [No connection]");
480                                 if(!(result & 4)) return _("Lyrics  [Not found]"); 
481                         }
482                 }
483                 if(lock == 2) return _("Lyrics  [retrieving]");
484         }
485         /*if(lyr_text.lines->len > 2) 
486         {
487                 static char buf[512];
488                 char artist[512];
489                 char title[512];
490                 get_text_line(&lyr_text, 0, artist, 512);
491                 get_text_line(&lyr_text, 1, artist, 512);
492                 snprintf(buf, 512, "Lyrics  %s - %s", artist, title);
493                 return buf;
494         }*/
495         return "Lyrics";
498 static void 
499 lyrics_paint(screen_t *screen, mpdclient_t *c)
501   lw->clear = 1;
502   list_window_paint(lw, list_callback, NULL);
503   wrefresh(lw->w);
506 static void 
507 lyrics_update(screen_t *screen, mpdclient_t *c)
508 {  
509   if( lw->repaint )
510     {
511       list_window_paint(lw, list_callback, NULL);
512       wrefresh(lw->w);
513       lw->repaint = 0;
514     }
518 static int 
519 lyrics_cmd(screen_t *screen, mpdclient_t *c, command_t cmd)
521   lw->repaint=1;
522   static retrieval_spec spec;
523   char *msg;
524   switch(cmd)
525     {
526     case CMD_LIST_NEXT:
527       if( lw->start+lw->rows < lyr_text.lines->len+1 )
528         lw->start++;
529       return 1;
530     case CMD_LIST_PREVIOUS:
531       if( lw->start >0 )
532         lw->start--;
533       return 1;
534     case CMD_LIST_FIRST:
535       lw->start = 0;
536       return 1;
537     case CMD_LIST_LAST:
538       lw->start = lyrics_text_rows-lw->rows;
539       if( lw->start<0 )
540         lw->start = 0;
541       return 1;
542     case CMD_LIST_NEXT_PAGE:
543       lw->start = lw->start + lw->rows-1;
544       if( lw->start+lw->rows >= lyr_text.lines->len+1 )
545         lw->start = lyr_text.lines->len-lw->rows+1;
546       if( lw->start<0 )
547         lw->start = 0;
548        return 1;
549     case CMD_LIST_PREVIOUS_PAGE:
550       lw->start = lw->start - lw->rows;
551       if( lw->start<0 )
552         lw->start = 0;
553       return 1;
554         case CMD_SELECT:
555           spec.client = c;
556           spec.way = 0;
557           g_thread_create(get_lyr, &spec, FALSE, NULL); 
558           return 1;
559         case CMD_INTERRUPT:
560           if(lock > 1) lock = 4;
561           return 1;     
562         case CMD_ADD:
563           if(lock > 0 && lock != 4)
564           {
565                  if(store_lyr_hd() == 0) screen_status_message (_("Lyrics saved!"));
566           }
567           return 1;
568         case CMD_LYRICS_UPDATE:
569           spec.client = c;
570           spec.way = 1;
571           g_thread_create(get_lyr, &spec, FALSE, NULL);
572         default:
573       break;
574     }
576   lw->selected = lw->start+lw->rows;
577   if( screen_find(screen, c, 
578                   lw,  lyrics_text_rows,
579                   cmd, list_callback, NULL) )
580     {
581       /* center the row */
582       lw->start = lw->selected-(lw->rows/2);
583       if( lw->start+lw->rows > lyrics_text_rows )
584         lw->start = lyrics_text_rows-lw->rows;
585       if( lw->start<0 )
586         lw->start=0;
587       return 1;
588     }
590   return 0;
593 static list_window_t *
594 lyrics_lw(void)
596   return lw;
599 screen_functions_t *
600 get_screen_lyrics(void)
602   static screen_functions_t functions;
604   memset(&functions, 0, sizeof(screen_functions_t));
605   functions.init   = lyrics_init;
606   functions.exit   = lyrics_exit;
607   functions.open   = NULL;
608   functions.close  = NULL;
609   functions.resize = lyrics_resize;
610   functions.paint  = lyrics_paint;
611   functions.update = lyrics_update;
612   functions.cmd    = lyrics_cmd;
613   functions.get_lw = lyrics_lw;
614   functions.get_title = lyrics_title;
616   return &functions;
618 #endif /* ENABLE_LYRICS_SCREEN */