Code

use older revision till serious bugfix
[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 #define _GNU_SOURCE
25 #include <stdlib.h>
26 #include <string.h>
27 #include <glib.h>
28 #include <ncurses.h>
29 #include <expat.h>
30 #include <unistd.h>
31 #include <glib/gstdio.h>
32 #include <stdio.h>
34 #include "config.h"
35 #ifndef DISABLE_LYRICS_SCREEN
36 #include <sys/stat.h>
37 #include "ncmpc.h"
38 #include "options.h"
39 #include "mpdclient.h"
40 #include "command.h"
41 #include "screen.h"
42 #include "screen_utils.h"
43 #include "easy_download.h"
44 #include "strfsong.h"
47 #define LEOSLYRICS_SEARCH_URL "http://api.leoslyrics.com/api_search.php?auth=ncmpc&artist=%s&songtitle=%s"
48  
49 #define LEOSLYRICS_CONTENT_URL "http://api.leoslyrics.com/api_lyrics.php?auth=ncmpc&hid=%s"
51 #define CREDITS "Lyrics provided by www.LeosLyrics.com"
52 typedef struct _formed_text
53 {
54         GString *text;
55         GArray *lines;
56         int val;
57 } formed_text;
59 typedef struct _retrieval_spec
60 {
61         mpdclient_t *client;
62         int way;
63 } retrieval_spec;
67 XML_Parser parser, contentp;
68 static int lyrics_text_rows = -1;
69 static list_window_t *lw = NULL;
70 guint8 result;
71 char *hid;
72 GTimer *dltime;
73 short int lock;
74 formed_text lyr_text;
75 /* result is a bitset in which the succes when searching 4 lyrics is logged
76 countend by position - backwards
77 0: lyrics in database
78 1: proper access  to the lyrics provider
79 2: lyrics found
80 3: exact match
81 4: lyrics downloaded
82 5: lyrics saved
83 wasting 3 bits doesn't mean being a fat memory hog like kde.... does it?
84 */
85 static void lyrics_paint(screen_t *screen, mpdclient_t *c);
87 int get_text_line(formed_text *text, int num, char *dest, int len)
88 {
89         memset(dest, '\0', len*sizeof(char));
90     if(num >= text->lines->len-1) return -1;    
91         int linelen;
92         if(num == 0)
93         {
94                 linelen = g_array_index(text->lines, int, num);
95                 memcpy(dest, text->text->str, linelen*sizeof(char));    
96         }
97         else if(num == 1)
98         { //dont ask me why, but this is needed....
99                 linelen = g_array_index(text->lines, int, num)
100                         - g_array_index(text->lines, int, num-1);
101                 memcpy(dest, &text->text->str[g_array_index(text->lines, int, num-1)],
102                 linelen*sizeof(char));  
103         }       
104         else
105         {
106                 linelen = g_array_index(text->lines, int, num+1)
107                         - g_array_index(text->lines, int, num);
108                 memcpy(dest, &text->text->str[g_array_index(text->lines, int, num)],
109                 linelen*sizeof(char));  
110         }
111         dest[linelen] = '\n';
112         dest[linelen+1] = '\0';
113         
114         return 0;
116         
117 void add_text_line(formed_text *dest, const char *src, int len)
119         // need this because g_array_append_val doesnt work with literals
120         // and expat sends "\n" as an extra line everytime
121         if(len == 0)
122         {
123                 dest->val = strlen(src);
124                 if(dest->lines->len > 0) dest->val += g_array_index(dest->lines, int,
125                                                                         dest->lines->len-1);
126                 g_string_append(dest->text, src);
127                 g_array_append_val(dest->lines, dest->val);
128                 return;
129         }
130         if(len > 1 || dest->val == 0) 
131         {
132                 dest->val = len;        
133                 if(dest->lines->len > 0) dest->val += g_array_index(dest->lines, int,
134                                                                         dest->lines->len-1);
135         }
136         else if (len == 1 && dest->val != 0) dest->val = 0;
137                                 
138         if(dest->val > 0)
139         { 
140                 g_string_append_len(dest->text, src, len);
141                 g_array_append_val(dest->lines, dest->val);
142         }
145 void formed_text_init(formed_text *text)
147         if(text->text != NULL) g_string_free(text->text, TRUE); 
148         text->text = g_string_new("");
149         
150         if(text->lines != NULL) g_array_free(text->lines, TRUE);
151         text->lines = g_array_new(FALSE, TRUE, 4);
152         
153         text->val = 0;
156 static void check_content(void *data, const char *name, const char **atts)
157
158         if(strstr(name, "text") != NULL)
159         {
161                 result |= 16;
162         }
164         
166 static void check_search_response(void *data, const char *name,
167                  const char **atts)
169         if(strstr(name, "response") != NULL)
170         {
171         result |=2;
172         return;
173         }  
174             
175         if(result & 4)
176         {
177                 if(strstr(name, "result") != NULL)
178                 {
179                         if(strstr(atts[2], "hid") != NULL)
180                         {
181                                 hid = atts[3];
182                         }
183         
184                         if(strstr(atts[2], "exactMatch") != NULL)
185                         {
186                                 result |= 8;
187                         }                       
188                 }
189         }
190                         
193 static void end_tag(void *data, const char *name)
195   //hmmmmmm             
198   static void check_search_success(void *userData, const XML_Char *s, int len)
199     {
200         if(result & 2)  //lets first check whether we're right
201         {               //we don't really want to search in the wrong string
202                 if(strstr((char*) s, "SUCCESS"))
203                 {
204                 result |=4;
205                 }
206         }       
207     }
209 static void fetch_text(void *userData, const XML_Char *s, int len) 
211         if(result & 16)
212         {
213                 add_text_line(&lyr_text, s, len); 
214         }
217 int check_dl_progress(void *clientp, double dltotal, double dlnow,
218                         double ultotal, double ulnow)
220         if(g_timer_elapsed(dltime, NULL) >= options.lyrics_timeout || lock == 4)
221         {       
222                 formed_text_init(&lyr_text);
223                 return -1;
224         }
226         return 0;
227 }       
230 int check_lyr_http(char *artist, char *title, char *url)
232         char url_avail[256];
234         //this replacess the whitespaces with '+'
235         g_strdelimit(artist, " ", '+');
236         g_strdelimit(title, " ", '+');
237         
238         //we insert the artist and the title into the url               
239         snprintf(url_avail, 512, LEOSLYRICS_SEARCH_URL, artist, title);
241         //download that xml!
242         easy_download_struct lyr_avail = {NULL, 0,-1};  
243         
244         g_timer_start(dltime);
245         if(!easy_download(url_avail, &lyr_avail, check_dl_progress)) return -1;
246         g_timer_stop(dltime);
248         //we gotta parse that stuff with expat
249         parser = XML_ParserCreate(NULL);
250         XML_SetUserData(parser, NULL);
251         
252         XML_SetElementHandler(parser, check_search_response, end_tag);
253         XML_SetCharacterDataHandler(parser, check_search_success);
254         XML_Parse(parser, lyr_avail.data, strlen(lyr_avail.data), 0);   
255         XML_ParserFree(parser); 
257         if(!(result & 4)) return -1; //check whether lyrics found
258         snprintf(url, 512, LEOSLYRICS_CONTENT_URL, hid);
260         return 0;
262 int get_lyr_http(char *artist, char *title)
264         char url_hid[256];
265         if(dltime == NULL) dltime = g_timer_new();
267         if(check_lyr_http(artist, title, url_hid) != 0) return -1;
268         
269         easy_download_struct lyr_content = {NULL, 0,-1};  
270         g_timer_continue(dltime);               
271         if(!(easy_download(url_hid, &lyr_content, check_dl_progress))) return -1;
272         g_timer_stop(dltime);
273         
274         contentp = XML_ParserCreate(NULL);
275         XML_SetUserData(contentp, NULL);
276         XML_SetElementHandler(contentp, check_content, end_tag);        
277         XML_SetCharacterDataHandler(contentp, fetch_text);
278         XML_Parse(contentp, lyr_content.data, strlen(lyr_content.data), 0);
279         XML_ParserFree(contentp);
281         return 0;
282         
284 FILE *create_lyr_file(char *artist, char *title)
286                 char path[1024];
288                 snprintf(path, 1024, "%s/.lyrics", 
289                         getenv("HOME"));
290                 if(g_access(path, W_OK) != 0) if(mkdir(path, S_IRWXU) != 0) return NULL;
291         
292                 snprintf(path, 1024, "%s/.lyrics/%s", 
293                                 getenv("HOME"), artist);
294                 if(g_access(path, W_OK) != 0) if(mkdir(path, S_IRWXU) != 0) return NULL;        
295         
296                 snprintf(path, 1024, "%s/.lyrics/%s/%s.lyric", 
297                                 getenv("HOME"), artist, title);
299             return fopen(path, "w");
300 }       
302 char *check_lyr_hd(char *artist, char *title, int how)
303 { //checking whether for lyrics file existence and proper access
304         static char path[1024];
305         snprintf(path, 1024, "%s/.lyrics/%s/%s.lyric", 
306                         getenv("HOME"), artist, title);
307     
308     if(g_access(path, how) != 0) return NULL;
309                  
310         return path;
311 }               
314 int get_lyr_hd(char *artist, char *title)
316         char *path = check_lyr_hd(artist, title, R_OK);
317         if(path == NULL) return -1;
318         
319         FILE *lyr_file; 
320         lyr_file = fopen(path, "r");
321         if(lyr_file == NULL) return -1;
322         
323         char *buf = NULL;
324         char **line = &buf;
325         size_t n = 0;
326         
327         while(1)
328         {
329          n = getline(line, &n, lyr_file); 
330          if( n < 1 || *line == NULL || feof(lyr_file) != 0 ) return 0;
331          add_text_line(&lyr_text, *line, n);
332          free(*line);
333          *line = NULL; n = 0;
334          }
335         
336         return 0;
337 }       
338     
339 int store_lyr_hd()
341         char artist[512];
342         char title[512];
343         static char path[1024];
344         FILE *lyr_file;
345         
346         get_text_line(&lyr_text, 0, artist, 512);
347         get_text_line(&lyr_text, 1, title, 512);
348         artist[strlen(artist)-1] = '\0';
349         title[strlen(title)-1] = '\0';
350         
351         snprintf(path, 1024, "%s/.lyrics/%s/%s.lyric", 
352                         getenv("HOME"), artist, title);
353         lyr_file = create_lyr_file(artist, title);
354         if(lyr_file == NULL) return -1;
355         int i;
356         char line_buf[1024];
357         
358         for(i = 3; i <= lyr_text.text->len; i++)
359         {
360                 if(get_text_line(&lyr_text, i, line_buf, 1024) == -1);
361                 fputs(line_buf, lyr_file);
362         }
363         fclose(lyr_file);
364         return 0;
366                                 
367         
368 void check_repaint()
370         if(screen_get_id("lyrics") == get_cur_mode_id())lyrics_paint(NULL, NULL);
374 gpointer get_lyr(void *c)
376         mpd_Status *status = ((retrieval_spec*)c)->client->status;
377         mpd_Song *cur = ((retrieval_spec*)c)->client->song; 
378         //mpdclient_update((mpdclient_t*)c);
379         
380         if(!(IS_PAUSED(status->state)||IS_PLAYING(status->state)))
381         {
382                 formed_text_init(&lyr_text);                    
383                 return NULL;
384         }
385         
387         char artist[MAX_SONGNAME_LENGTH];
388         char title[MAX_SONGNAME_LENGTH];
389         lock = 2;
390         result = 0;
391         
392         formed_text_init(&lyr_text);
393         
394         strfsong(artist, MAX_SONGNAME_LENGTH, "%artist%", cur);
395         strfsong(title, MAX_SONGNAME_LENGTH, "%title%", cur);
396         
397         //write header..
398         formed_text_init(&lyr_text);
399         add_text_line(&lyr_text, artist, 0);
400         add_text_line(&lyr_text, title, 0);
401         add_text_line(&lyr_text, "", 0);
402         add_text_line(&lyr_text, "", 0);
403         
404         if (((retrieval_spec*)c)->way == 1)
405         {
406                  if(get_lyr_http(artist, title) != 0) return NULL;
407         }
408         else{
409                 if(get_lyr_hd(artist, title) != 0) 
410                 {
411                 if(get_lyr_http(artist, title) != 0) return NULL;
412                 }
413                 else result |= 1;
414         }
415         
416         lw->start = 0;
417         check_repaint();
418         lock = 1;
419         return &lyr_text;
420 }       
422 static char *
423 list_callback(int index, int *highlight, void *data)
425         static char buf[512];
426         
427     //i think i'ts fine to write it into the 1st line...
428   if((index == lyr_text.lines->len && lyr_text.lines->len > 4)||
429           ((lyr_text.lines->len == 0 
430           ||lyr_text.lines->len == 4) && index == 0))
431   {
432     *highlight=3; 
433           return CREDITS;
434   }
435     
436   if(index < 2 && lyr_text.lines->len > 4) *highlight=3;
437   else if(index >=  lyr_text.lines->len ||
438         ( index < 4 && index != 0 && lyr_text.lines->len < 5))
439   {
440           return "";
441   }
442  
443   get_text_line(&lyr_text, index, buf, 512);
444   return buf;
445
448 static void
449 lyrics_init(WINDOW *w, int cols, int rows)
451   lw = list_window_init(w, cols, rows);
452   lw->flags = LW_HIDE_CURSOR;
453   //lyr_text.lines = g_array_new(FALSE, TRUE, 4);
454   formed_text_init(&lyr_text);
455   if (!g_thread_supported()) g_thread_init(NULL);
456   
459 static void
460 lyrics_resize(int cols, int rows)
462   lw->cols = cols;
463   lw->rows = rows;
466 static void
467 lyrics_exit(void)
469   list_window_free(lw);
473 static char *
474 lyrics_title(char *str, size_t size)
476         if(lyr_text.lines->len == 4)
477         {
478                 if(lock == 1)
479                 {
480                         if(!(result & 1))
481                         {
482                                 if(!(result & 2)) return _("Lyrics  [No connection]");
483                                 if(!(result & 4)) return _("Lyrics  [Not found]"); 
484                         }
485                 }
486                 if(lock == 2) return _("Lyrics  [retrieving]");
487         }
488         /*if(lyr_text.lines->len > 2) 
489         {
490                 static char buf[512];
491                 char artist[512];
492                 char title[512];
493                 get_text_line(&lyr_text, 0, artist, 512);
494                 get_text_line(&lyr_text, 1, artist, 512);
495                 snprintf(buf, 512, "Lyrics  %s - %s", artist, title);
496                 return buf;
497         }*/
498         return "Lyrics";
501 static void 
502 lyrics_paint(screen_t *screen, mpdclient_t *c)
504   lw->clear = 1;
505   list_window_paint(lw, list_callback, NULL);
506   wrefresh(lw->w);
509 static void 
510 lyrics_update(screen_t *screen, mpdclient_t *c)
511 {  
512   if( lw->repaint )
513     {
514       list_window_paint(lw, list_callback, NULL);
515       wrefresh(lw->w);
516       lw->repaint = 0;
517     }
521 static int 
522 lyrics_cmd(screen_t *screen, mpdclient_t *c, command_t cmd)
524   lw->repaint=1;
525   static retrieval_spec spec;
526   switch(cmd)
527     {
528     case CMD_LIST_NEXT:
529       if( lw->start+lw->rows < lyr_text.lines->len+1 )
530         lw->start++;
531       return 1;
532     case CMD_LIST_PREVIOUS:
533       if( lw->start >0 )
534         lw->start--;
535       return 1;
536     case CMD_LIST_FIRST:
537       lw->start = 0;
538       return 1;
539     case CMD_LIST_LAST:
540       lw->start = lyrics_text_rows-lw->rows;
541       if( lw->start<0 )
542         lw->start = 0;
543       return 1;
544     case CMD_LIST_NEXT_PAGE:
545       lw->start = lw->start + lw->rows-1;
546       if( lw->start+lw->rows >= lyr_text.lines->len+1 )
547         lw->start = lyr_text.lines->len-lw->rows+1;
548       if( lw->start<0 )
549         lw->start = 0;
550        return 1;
551     case CMD_LIST_PREVIOUS_PAGE:
552       lw->start = lw->start - lw->rows;
553       if( lw->start<0 )
554         lw->start = 0;
555       return 1;
556         case CMD_SELECT:
557           spec.client = c;
558           spec.way = 0;
559           g_thread_create(get_lyr, &spec, FALSE, NULL); 
560           return 1;
561         case CMD_INTERRUPT:
562           if(lock > 1) lock = 4;
563           return 1;     
564         case CMD_ADD:
565           if(lock > 0 && lock != 4)
566           {
567                    if(store_lyr_hd() == 0) screen_status_message (_("Lyrics saved!"));
568           }
569           return 1;
570         case CMD_LYRICS_UPDATE:
571           spec.client = c;
572           spec.way = 1;
573           g_thread_create(get_lyr, &spec, FALSE, NULL);
574         default:
575       break;
576     }
578   lw->selected = lw->start+lw->rows;
579   if( screen_find(screen, c, 
580                   lw,  lyrics_text_rows,
581                   cmd, list_callback, NULL) )
582     {
583       /* center the row */
584       lw->start = lw->selected-(lw->rows/2);
585       if( lw->start+lw->rows > lyrics_text_rows )
586         lw->start = lyrics_text_rows-lw->rows;
587       if( lw->start<0 )
588         lw->start=0;
589       return 1;
590     }
592   return 0;
595 static list_window_t *
596 lyrics_lw(void)
598   return lw;
601 screen_functions_t *
602 get_screen_lyrics(void)
604   static screen_functions_t functions;
606   memset(&functions, 0, sizeof(screen_functions_t));
607   functions.init   = lyrics_init;
608   functions.exit   = lyrics_exit;
609   functions.open   = NULL;
610   functions.close  = NULL;
611   functions.resize = lyrics_resize;
612   functions.paint  = lyrics_paint;
613   functions.update = lyrics_update;
614   functions.cmd    = lyrics_cmd;
615   functions.get_lw = lyrics_lw;
616   functions.get_title = lyrics_title;
618   return &functions;
620 #endif /* ENABLE_LYRICS_SCREEN */