Source

astrosearch / SimpleStats.hs

Full commit
  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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}

{-

Usage:

  ./simplestats [json] <endpoint> <nvals>

Aim:

Perform some simple stats

  - most retweeted status
  - most retweeted user
  - most mentioned user
  - most mentioned hashtag

and return them (nvals is the number of values to use in each
category).

Notes:

Have seen

  simplestats: recv: resource vanished (Connection reset by peer)

which exited the program, when trying to resolve URLs.

-}

module Main where

import qualified Control.Exception as CE
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Lazy.Char8 as LB
import qualified Data.Conduit as C
import qualified Data.IntMap as IM
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as UV
import qualified Network.URI as N
import qualified Statistics.Sample.Histogram as H

import Control.Exception (bracket)
import Control.Monad (forM_, void, when)

import Data.Acid hiding (Query)
import Data.Aeson
import Data.List (foldl', groupBy, sort)
import Data.Maybe (fromMaybe, fromJust)
import Data.Time (UTCTime, NominalDiffTime, diffUTCTime)
import Database.HaSparqlClient (Query, NamedGraph, BindingValue(..))

import Network.HTTP.Conduit ( Manager, HttpException(..), Request, Response(..)
                            , getRedirectedRequest, http, method, parseUrl
			    , redirectCount, simpleHttp
			    , closeManager, newManager, def
                            , secure, host, port, path, queryString
                            , requestHeaders
			    )
import Network.HTTP.Types.Header (Header, RequestHeaders, hUserAgent)
import Network.HTTP.Types.Status (Status(..))

import System.Environment (getArgs, getProgName)
import System.Exit (exitFailure)
import System.IO (stderr, hPutStrLn)

import AcidState ( SimpleStatsStore, URIInfo(..)
                 , AddOEmbed(..), GetOEmbed(..)
                 , AddURL(..), GetURL(..)
                 , emptySimpleStatsStore)
import SPARQL ( FromBinding(..), UserId, BasicUserInfo, BasicTweetCount(..)
              , FollowerInfo(..)
       	      , Counter(..)
	      , CounterList, SortedList, toSortedCL, takeCL, fromCL, mapMCL
              , makeQuery, queryStore, fromStores
              , to1, to2, toCounter
              , getUserName, getUserHandle
              , getUserTweetCount
              , getTimeRange, getBasicUserInfo, getNumberFollowInfo
              )
import Utils (maybeRead)

instance ToJSON N.URI where
    toJSON = toJSON . show

instance ToJSON a => ToJSON (Counter a) where
  toJSON (Counter a b) = 
    object [ "count" .= b
           , "label" .= a
           ]
  
type Hist = [(Int, Int)]

type Sorted a = CounterList a SortedList
type SortedUsers = Sorted UserId

type QueryResponse =
    ( Int  -- ^ number of accounts that tweeted
    , Int  -- ^ number of accounts that *only* retweeted
    , Int  -- ^ number of tweets
    , Int  -- ^ number of retweets
    , Int  -- ^ number of tweets that included the publisher information
    , Hist -- ^ retweet histogram
    , Hist -- ^ user tweet histogram
    , Hist -- ^ user retweet histogram
    , Hist -- ^ number of different publishers used by a user 
    , V.Vector KDE  -- ^ KDE for the time-to-retweet values (10 minutes)
    , V.Vector KDE  -- ^ KDE for the time-to-retweet values (6 hour)
    , Sorted Object  -- ^ JSON from Twitter containing the contents of the
                     --   most-tweeted statuses
    , SortedUsers    -- ^ the accounts that were replied to the most (excl RTs)
    , SortedUsers    -- ^ the accounts that made the most replies (excl RTs)
    , SortedUsers    -- ^ the most re-tweeted accounts
    , SortedUsers    -- ^ the most-mentioned accounts
    , Sorted String  -- ^ the most-mentioned hash tags
    , Sorted URIInfo -- ^ the most-mentioned URLs
    , Sorted T.Text  -- ^ the most-used publishers
    , [(Int, Int, Int, Int)] -- ^ num friends, num followers, total num of tweets, num of retweets
    , M.Map UserId BasicUserInfo -- ^ map from user id to user labels
    , UTCTime -- ^ approximate time of first tweet (or when the search was made)
    , UTCTime -- ^ approximate time of last tweet (or when the search was made)
    )

newtype KDE = K (Double, Double)
              deriving (Eq, Show)
                       
instance ToJSON KDE where                       
  toJSON (K c) = toJSON c

{- For now we are not interested in dumping out the status codes -}
instance ToJSON URIInfo where
  toJSON (URIInfo _ u) = toJSON u
  
-- Find the number of retweets per tweet.
--
-- We need ?tweetid in the select line to avoid the sum being done
-- on all the tweets, but we do not actually need the id in the
-- output.
--
-- The reason for using ?tweetid is so that we can use toCounter
-- when converting the results.
queryRetweetCount :: [NamedGraph] -> Query
queryRetweetCount ngs = 
  unwords
  [ "prefix sioc: <http://rdfs.org/sioc/ns#>"
  , "prefix sioct: <http://rdfs.org/sioc/types#>"
  , "prefix tw: <http://purl.org/net/djburke/demo/twitter#>"
  , "SELECT ?tweetid (COUNT(?rtw) as ?nrtws) "
  , fromStores ngs
  , " WHERE {"
  , "  ?tw a sioct:MicroblogPost ; sioc:id ?tweetid ."
  , "  OPTIONAL { ?tw tw:isRetweet ?f }" -- relies on ?f only ever being True
  , "  FILTER (!BOUND(?f))"
  , "  OPTIONAL {"
  , "    ?rtw sioc:reply_of ?tw ; a sioct:MicroblogPost ; tw:isRetweet True ."
  , "  }"
  , "}"
  , "GROUP BY ?tweetid"
  ]

queryMostRetweetedStatus :: [NamedGraph] -> Query
queryMostRetweetedStatus ngs =
  unwords
  [ "prefix sioc: <http://rdfs.org/sioc/ns#>"
  , "prefix sioct: <http://rdfs.org/sioc/types#>"
  , "prefix tw: <http://purl.org/net/djburke/demo/twitter#>"
  , "SELECT ?tweetid (COUNT(?rt) as ?nrts) "
  , fromStores ngs
  , " WHERE {"
  , "  ?rt sioc:reply_of [ a sioct:MicroblogPost ; sioc:id ?tweetid ] ;"
  , "      tw:isRetweet True ."
  , "}"
  , "GROUP BY ?tweetid"
  ]

-- Note that we remove explicit retweets
queryMostRepliedToUser :: [NamedGraph] -> Query
queryMostRepliedToUser ngs =
  unwords
  [ "prefix sioc: <http://rdfs.org/sioc/ns#>"
  , "prefix sioct: <http://rdfs.org/sioc/types#>"
  , "prefix tw: <http://purl.org/net/djburke/demo/twitter#>"
  , "SELECT ?userid (COUNT(?rt) as ?nreplies) "
  , fromStores ngs
  , " WHERE {"
  , "  ?rt sioc:reply_of [ a sioct:MicroblogPost ; sioc:has_creator [ sioc:id ?userid ] ] ."
  , "  OPTIONAL { ?rt tw:isRetweet ?f }" -- relies on ?f only ever being True
  , "  FILTER (!BOUND(?f))"
  , "}"
  , "GROUP BY ?userid"
  ]

-- Note that we remove explicit retweets
queryUserMakesMostReplies :: [NamedGraph] -> Query
queryUserMakesMostReplies ngs =
  unwords
  [ "prefix sioc: <http://rdfs.org/sioc/ns#>"
  , "prefix sioct: <http://rdfs.org/sioc/types#>"
  , "prefix tw: <http://purl.org/net/djburke/demo/twitter#>"
  , "SELECT ?userid (COUNT(?rt) as ?nreplies) "
  , fromStores ngs
  , " WHERE {"
  , "  ?rt sioc:reply_of [ a sioct:MicroblogPost ] ;"
  , "      sioc:has_creator [ a sioc:UserAccount ; sioc:id ?userid ] ."
  , "  OPTIONAL { ?rt tw:isRetweet ?f }" -- relies on ?f only ever being True
  , "  FILTER (!BOUND(?f))"
  , "}"
  , "GROUP BY ?userid"
  ]

queryMostRetweetedUser :: [NamedGraph] -> Query
queryMostRetweetedUser ngs =
  unwords
  [ "prefix sioc: <http://rdfs.org/sioc/ns#>"
  , "prefix sioct: <http://rdfs.org/sioc/types#>"
  , "prefix tw: <http://purl.org/net/djburke/demo/twitter#>"
  , "SELECT ?userid (COUNT(?rt) as ?nrts) "
  , fromStores ngs
  , " WHERE {"
  , "  ?rt sioc:reply_of [ a sioct:MicroblogPost ; sioc:has_creator [ sioc:id ?userid ] ] ;"
  , "      tw:isRetweet True ."
  , "}"
  , "GROUP BY ?userid"
  ]

queryMostMentionedUser :: [NamedGraph] -> Query
queryMostMentionedUser ngs =
  unwords
  [ "prefix sioc: <http://rdfs.org/sioc/ns#>"
  , "prefix sioct: <http://rdfs.org/sioc/types#>"
  , "prefix dcterms: <http://purl.org/dc/terms/>"
  , "SELECT ?userid (COUNT(?tw) as ?ntws) "
  , fromStores ngs
  , " WHERE {"
  , "  ?tw a sioct:MicroblogPost ; dcterms:references [ sioc:id ?userid ] ."
  , "}"
  , "GROUP BY ?userid"
  ]

queryMostMentionedHashTag :: [NamedGraph] -> Query
queryMostMentionedHashTag ngs =
  unwords
  [ "prefix sioc: <http://rdfs.org/sioc/ns#>"
  , "prefix sioct: <http://rdfs.org/sioc/types#>"
  , "prefix lode: <http://linkedevents.org/ontology/>"
  , "SELECT ?hashtag (COUNT(?tw) as ?ntws) "
  , fromStores ngs
  , " WHERE {"
  , "  ?tw a sioct:MicroblogPost ; lode:illustrate ?hashtag ."
  , "}"
  , "GROUP BY ?hashtag"
  ]

queryMostMentionedURL :: [NamedGraph] -> Query
queryMostMentionedURL ngs =
  unwords
  [ "prefix sioc: <http://rdfs.org/sioc/ns#>"
  , "prefix sioct: <http://rdfs.org/sioc/types#>"
  , "SELECT ?url (COUNT(?tw) as ?ntws) "
  , fromStores ngs
  , " WHERE {"
  , "  ?tw a sioct:MicroblogPost ; sioc:links_to ?url ."
  , "}"
  , "GROUP BY ?url"
  ]

-- Is there an extension function for subtracting dates?
queryTimeToRetweet :: [NamedGraph] -> Query
queryTimeToRetweet ngs = 
  unwords
  [ "prefix sioc: <http://rdfs.org/sioc/ns#>"
  , "prefix sioct: <http://rdfs.org/sioc/types#>"
  , "prefix tw: <http://purl.org/net/djburke/demo/twitter#>"
  , "prefix dcterms: <http://purl.org/dc/terms/>"
  , "SELECT ?otime ?rtime "
  , fromStores ngs
  , " WHERE {"
  , "  [] a sioct:MicroblogPost ; dcterms:created ?rtime ;"
  , "     tw:isRetweet True;"
  , "     sioc:reply_of ["
  , "       a sioct:MicroblogPost ; dcterms:created ?otime"
  , "     ] ."
  , "}"
  ]

queryPublisherCount :: [NamedGraph] -> Query
queryPublisherCount ngs = 
  unwords
  [ "prefix sioct: <http://rdfs.org/sioc/types#>"
  , "prefix dcterms: <http://purl.org/dc/terms/>"
  , "SELECT ?publisher (COUNT(?tw) as ?ntweets) "
  , fromStores ngs
  , " WHERE {"
  , "  ?tw a sioct:MicroblogPost ; dcterms:publisher ?publisher ."
  , "} GROUP BY ?publisher"
  ]

{-
As I have not declared a "type" for publishers, we have to use
the constraint 
   [] a sioct:MicroblogPost ; dcterms:publisher ?publisher
- or just [] dcterms:publisher ?publisher but the above is a bit
more specific - which means that we get back a label for each tweet,
even when they are the same label. This means we can not use
GROUP_CONCAT. I could use SAMPLE to just pick one; this seems like
a good idea, so do that.
-}
queryPublisherInfo :: [NamedGraph] -> Query
queryPublisherInfo ngs = 
  unwords
  [ "prefix sioct: <http://rdfs.org/sioc/types#>"
  , "prefix dcterms: <http://purl.org/dc/terms/>"
  , "prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>"
  , "SELECT ?publisher (SAMPLE(?labels) as ?label) "
  , fromStores ngs
  , " WHERE {"
  , "  [] a sioct:MicroblogPost ; dcterms:publisher ?publisher ."
  , "  ?publisher rdfs:label ?labels ."
  , "} GROUP BY ?publisher"
  ]

-- Look at how many different "publishers" a user used.
--
-- For the moment we do not include the actual publishers used
queryUserPublisherCount :: [NamedGraph] -> Query
queryUserPublisherCount ngs = 
  unwords
  [ "prefix sioc: <http://rdfs.org/sioc/ns#>"
  , "prefix sioct: <http://rdfs.org/sioc/types#>"
  , "prefix dcterms: <http://purl.org/dc/terms/>"
  -- , "SELECT ?userid ?publisher (COUNT(?publisher) as ?ntw) "
  , "SELECT ?userid (COUNT(?publisher) as ?ntw) "
  , fromStores ngs
  , " WHERE {"
  , "  [] a sioct:MicroblogPost ; dcterms:publisher ?publisher ; sioc:has_creator [ sioc:id ?userid ] ."
  , "} GROUP BY ?userid ?publisher"
  ]

getCount :: [BindingValue] -> Maybe Int
getCount (_:bv:[]) = fromBinding bv
getCount _ = Nothing

toNum :: [BindingValue] -> Maybe Int
toNum = to1

-- Given time1 and time2 return (time2-time1)
toDelta :: [BindingValue] -> Maybe NominalDiffTime
toDelta = (uncurry (flip diffUTCTime) `fmap`) . to2

toFollowerCount :: M.Map UserId BasicTweetCount -> [BindingValue] -> Maybe (Int, Int, Int, Int)
toFollowerCount uMap (uidbv:nfriendbv:nfollowerbv:[]) = do
  uid <- fromBinding uidbv
  BasicTweetCount {..} <- M.lookup uid uMap
  nfriend <- fromBinding nfriendbv
  nfollower <- fromBinding nfollowerbv
  return (nfriend, nfollower, btcNTweets, btcNRetweets)

toFollowerCount _ _ = Nothing

logIt :: String -> IO ()
logIt = hPutStrLn stderr

logException :: CE.SomeException -> IO ()
logException = logIt . ("EXCEPTION: " ++) . show 

-- | I really should not be creating a new connection for each query but this
--   is easier. Fortunately the GET endpoint is still working at the time of AAS221.
getFromTwitter :: Integer -> IO (Maybe T.Text)
getFromTwitter twId = 
    let url = "https://api.twitter.com/1/statuses/oembed.json?id=" ++ show twId ++ "&omit_script=true"
    in fmap (Just . TE.decodeUtf8 . B.concat . LB.toChunks) (simpleHttp url)
       `CE.catch` (\e -> logException e >> return Nothing)

getTweetInfo :: AcidState SimpleStatsStore -> Integer -> IO (Maybe T.Text)
getTweetInfo acid twId = do
  mtxt <- query acid (GetOEmbed twId)
  case mtxt of
    Just _ -> return mtxt
    _ -> do
      logIt $ "Looking for oEmbed data for tweet " ++ show twId
      mrsp <- getFromTwitter twId
      case mrsp of 
        Just rsp -> update acid (AddOEmbed twId rsp) >> return mrsp
        _ -> logIt " -- NONE FOUND!" >> return Nothing

-- | Get the JSON representation from the AcidState store or
--   Twitter OEmbed service. If we can not get a value then
--   it is excluded.
--
--   The restriction to a `SortedList` is not required by the
--   routine.
--
requestTweetInfo :: CounterList Integer SortedList -> IO (CounterList Object SortedList)
requestTweetInfo cs = 
    bracket
    (openLocalStateFrom "simplestats" emptySimpleStatsStore)
    closeAcidState
    (\acid -> 
     let toObj :: Integer -> IO (Maybe Object)
         toObj ci = do
           mtxt <- getTweetInfo acid ci
           case mtxt of
             Nothing  -> return Nothing
             Just txt -> return $ decode' (LB.fromChunks [TE.encodeUtf8 txt])
                      
     in mapMCL toObj cs
    )

{-| Convert a set of counts into a histogram; the bin
size is fixed at 1 and the input array is assumed to be
small, so do not need to make this particularly efficient.
-}
toHistogram :: [Int] -> Hist
toHistogram cnts = 
    let maxVal = maximum cnts
        minVal = minimum cnts
        cMap = foldl' (\omap k -> IM.insertWith' (+) k 1 omap) IM.empty cnts
        xHist = [minVal .. maxVal]
        yHist = map (\k -> IM.findWithDefault 0 k cMap) xHist
    in zip xHist yHist

{-
As the URLs may well be via a link-shortener service, I want
to decode them so that
  a) the user is presented with something more meaningfull
  b) if there are multiple occurrences of the same URL with
     different shorteners we can combine the data

For now we do nothing
-}
processURLs :: [Counter N.URI] -> IO (Sorted URIInfo)
processURLs = consolidateUrls . map (fmap show)

{-
Run the queries against the given endpoint, collecting
up the results. The counters are sorted in descending order.
-}
querySPARQL :: 
    String  -- ^ end point
    -> Int  -- ^ max number of values to return for each search
    -> IO QueryResponse
querySPARQL endpoint nmax = do
  stores <- queryStore endpoint
  (firstTime, lastTime) <- getTimeRange endpoint stores

  -- map from user id to #tweets (no retweets) and #retweets
  countMap <- getUserTweetCount endpoint stores
  let sumIt (nt,nrt) BasicTweetCount {..} =
          (nt + btcNStatus, nrt + btcNRetweets)
      (ntws, nrtws) = M.foldl' sumIt (0,0) countMap

      userTweetCount   = M.elems $ M.filter (>0) $ M.map btcNStatus countMap
      userRetweetCount = M.elems $ M.map btcNRetweets countMap -- do not filter out 0 element tweets
      onlyRetweetMap   = M.filter (\BasicTweetCount {..} -> btcNStatus == 0) countMap

  retweetStatus    <- makeQuery toCounter endpoint (queryMostRetweetedStatus stores)
  retweetCount     <- makeQuery getCount  endpoint (queryRetweetCount stores)
  repliedUser      <- makeQuery toCounter endpoint (queryMostRepliedToUser stores)
  garrulousUser    <- makeQuery toCounter endpoint (queryUserMakesMostReplies stores)
  retweetUser      <- makeQuery toCounter endpoint (queryMostRetweetedUser stores)
  mentionedUser    <- makeQuery toCounter endpoint (queryMostMentionedUser stores)
  mentionedHashTag <- makeQuery toCounter endpoint (queryMostMentionedHashTag stores)
  mentionedURL     <- makeQuery toCounter endpoint (queryMostMentionedURL stores)
  reTweetTimes     <- makeQuery toDelta   endpoint (queryTimeToRetweet stores)

  publisherCount   <- makeQuery toCounter endpoint (queryPublisherCount stores)
  userPubCount     <- makeQuery toCounter endpoint (queryUserPublisherCount stores)
  publisherInfo    <- makeQuery to2       endpoint (queryPublisherInfo stores)

  followerInfo     <- getNumberFollowInfo endpoint stores
  uinfo            <- getBasicUserInfo endpoint stores

  -- for now assume countMap and followerInfo have the same set of users in them
  let toFC :: BasicTweetCount -> FollowerInfo -> (Int, Int, Int, Int)
      toFC BasicTweetCount {..} FollowerInfo {..} = (fiNumFollows, fiNumFollowers, btcNTweets, btcNRetweets)
      followerCount = M.elems $ M.intersectionWith toFC countMap followerInfo

  let f :: (Ord a) => [Counter a] -> CounterList a SortedList
      f = takeCL nmax . toSortedCL

  tws <- requestTweetInfo $ f retweetStatus

  urls <- processURLs mentionedURL

  let rtwDelta10MinHist = calcHist 600.0 reTweetTimes
      rtwDelta6HourHist = calcHist 21600.0 reTweetTimes

      -- replace URI by label for publishers; we assume that there is
      -- always a label
      convPublisher :: N.URI -> T.Text
      convPublisher = fromJust . (`lookup` publisherInfo)
      pCount = map (fmap convPublisher) publisherCount
      
      nPub = foldl' (\c ctr -> c + _count ctr) 0 publisherCount

      -- fix the type for toCounter when creating userPubCount
      uidEq :: UserId -> UserId -> Bool
      uidEq = (==)

      userPub = map length $ groupBy uidEq $ sort $ map _value userPubCount

  return ( M.size countMap
         , M.size onlyRetweetMap
         , ntws, nrtws, nPub
         , toHistogram retweetCount
         , toHistogram userTweetCount
         , toHistogram userRetweetCount
         , toHistogram userPub
         , rtwDelta10MinHist
         , rtwDelta6HourHist
         , tws
	 , f repliedUser
	 , f garrulousUser
	 , f retweetUser
         , f mentionedUser
	 , f mentionedHashTag
         , takeCL nmax urls
         , f pCount
	 , followerCount
         , uinfo, firstTime, lastTime)

{-
Instead of a KDE, just create a histogram.
-}
calcSimpleHist ::
  Double
  -> [Double]
  -> V.Vector KDE
calcSimpleHist binsize vs =
  let v = UV.fromList vs
      vlo = 0.0 -- UV.minimum v
      vhi = UV.maximum v

      vdiff = vhi - vlo
      npts = ceiling $ vdiff / binsize

      dx = binsize
      xlo = vlo
      xhi = xlo + fromIntegral npts * dx

      xs = UV.enumFromStepN (xlo + dx/2) dx npts
      ys = H.histogram_ npts xlo xhi v

  in V.map K $ UV.convert $ UV.zip xs ys

calcHist ::
  Double  -- bin size in seconds
  -> [NominalDiffTime]
  -> V.Vector KDE
calcHist binsize = calcSimpleHist binsize . map (fromRational . toRational)

{-
Extract a URI from a request. I am assuming that if
the URL was in the request then it's valid, which assumes I am
re-constructing things correctly.
-}
req2URL :: Request m -> N.URI
req2URL req = 
  let pt = port req
      m = if secure req
          then "https:" ++ if pt == 443 then "" else show pt
          else "http:"  ++ if pt == 80 then "" else show pt

  in fromJust $ N.parseURI $ concat 
         [ m
         , "//"
         , B8.unpack (host req)
	 , B8.unpack (path req)
	 , B8.unpack (queryString req)]

{-
Given an exception, try and return something useful. I need to work out
whether I need the Maybe here or whether I want to record the error
using a "status code" of 0.
-}
getStatusCode :: N.URI -> HttpException -> IO (Maybe URIInfo)
getStatusCode uri (StatusCodeException s _) = do
  logIt $ " -- status code exception " ++ show s
  return $ Just $ URIInfo [statusCode s] uri
getStatusCode uri e = do
  logIt $ " -- other HTTP exception: " ++ show e
  return $ Just $ URIInfo [0] uri

{-
We store the last URL in the chain.
-}
toURIInfo :: [(Int, N.URI)] -> Maybe URIInfo
toURIInfo [] = Nothing
toURIInfo xs = 
    let (sts, uris) = unzip xs
    in Just $ URIInfo sts (last uris)

{-
Attempt to resolve link shorteners to their original URL,
retaining the input if there was no redirect, or an error
when accessing the URL (eg 404).

We first query the AcidState and then perform
a URL lookup if it is not known (adding the data
to the store).

I should be sending in manager here, rather than creating
one for each request, but for now avoid that hassle
(i.e. I couldn't be bothered fighting the types).

Note that I spoof ther user agent string to appear like a Chrome 12
browser running on OS-X 10.6.8 since this avoids getting
facebook pointing to http://www.facebook.cim/unsupportedbrowser.
-}

uAgent :: Header
uAgent = (hUserAgent, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.112 Safari/534.30")

changeUserAgent :: RequestHeaders -> RequestHeaders
changeUserAgent = go False
    where
      go False [] = [uAgent]
      go True  [] = []
      go f (hdr@(hname,_):hdrs)
          | hname == hUserAgent = uAgent : hdrs
          | otherwise           = hdr : go f hdrs

findRedirect :: 
    AcidState SimpleStatsStore
    -> String
    -> IO (Maybe URIInfo)
findRedirect acid orig = do
    ans <- query acid (GetURL orig)
    case ans of
      Just _ -> return ans
      -- Just _ -> logIt ("** Found URL in store " ++ orig) >> return ans -- DEBUG
      Nothing -> do
        logIt $ "Status of URL: " ++ orig
        rval <- getUrlInfo orig
	logIt $ "  -> " ++ show rval
	case rval of
	  Just ri -> void $ update acid (AddURL orig ri)
	  Nothing -> return ()
	return rval

getUrlInfo :: String -> IO (Maybe URIInfo)
getUrlInfo ustr = 
    case N.parseURI ustr of
      Nothing -> logIt ("*** Unable to parse URI " ++ ustr) >> return Nothing
      Just _ -> do
        ireq <- parseUrl ustr
        let ohdrs = requestHeaders ireq
            nhdrs = changeUserAgent ohdrs
            mreq = ireq { method = "HEAD", requestHeaders = nhdrs }
        -- rsps <- withManager (handleRedirect mreq)
        rsps <- bracket
                (newManager def)
                closeManager
                (handleRedirect mreq)

        return $ toURIInfo rsps

{-
Follow the redirects, recording the status value and URI at each step.

For some reason I am getting a cycle when following www.planethunters.org/,
since I get

URI: http://www.planethunters.org
Requesting: http://www.planethunters.org/
---> redirect https://login.zooniverse.org/login?service=http%3A%2F%2Fwww.planethunters.org%2F&gateway=true
Requesting: https://login.zooniverse.org/login?service=http%3A%2F%2Fwww.planethunters.org%2F&gateway=true
---> redirect http://www.planethunters.org/
======> CYCLE
(302,http://www.planethunters.org/)
(302,https://login.zooniverse.org/login?service=http%3A%2F%2Fwww.planethunters.org%2F&gateway=true)

so I've added a very basic cycle-detection system. The current system returns the
second one (ie the login version) as the "canonical" URI, but I do not feel like
tweaking things for this case.

-}
handleRedirect :: Request (C.ResourceT IO) -> Manager -> IO [(Int, N.URI)]
handleRedirect = go []
    where
      go seen req mgr = 
          let req' = req { redirectCount = 0 }
              uri = req2URL req'

              eHandle :: HttpException -> IO [(Int, N.URI)]
              eHandle (StatusCodeException s h) = 
                  let status = statusCode s
                      rval = (status, uri)
                  in if status >= 300 && status < 400
                     then case getRedirectedRequest req' h status of
                            Just rdr -> do
                              let nuri = req2URL rdr
                              logIt ("---> redirect " ++ show nuri)
                              if nuri `elem` seen
                                then logIt "======> CYCLE" >> return [rval] -- not sure what to return here
                                else do
                                  l <- go (uri:seen) rdr mgr
                                  return (rval : l)

                            _ -> return [rval] -- not sure what to return here

                     else logIt ("*** STATUS == " ++ show status) >> return [rval]
              eHandle e = logIt ("*** HTTP EXCEPTION " ++ show e) >> return [(0, uri)]

              ioHandle :: CE.IOException -> IO [(Int, N.URI)]
              ioHandle e = logIt ("*** IO EXCEPTION " ++ show e) >> return [(0, uri)]

          in C.runResourceT 
                 (http req' mgr >>= \(Response status _ _ _) -> return [(statusCode status, req2URL req')])
             `CE.catch` eHandle
             `CE.catch` ioHandle

{-

Without cycle detection
handleRedirect req mgr = 
    let req' = req { redirectCount = 0 }
        uri = req2URL req'
        eHandle (StatusCodeException s h) = 
            let status = statusCode s
                rval = (status, uri)
            in if status >= 300 && status < 400
               then case getRedirectedRequest req' h status of
                      Just rdr -> do
                        l <- handleRedirect rdr mgr
                        return (rval : l)
                      _ -> return [rval] -- not sure what to return here
               else return [rval]
        eHandle e = logIt ("*** HTTP EXCEPTION " ++ show e) >> return [(0, uri)]

        ioHandle :: CE.IOException -> IO [(Int, N.URI)]
        ioHandle e = logIt ("*** IO EXCEPTION " ++ show e) >> return [(0, uri)]

    in C.runResourceT 
          (http req' mgr >>= \(Response status _ _ _) -> return [(statusCode status, req2URL req')])
       `CE.catch` eHandle
       `CE.catch` ioHandle

-}

{-
Ensure we use the "canonical" URL value, by resolving
redirects, and then combining counts where necessary.
The output array may be smaller than the input one,
and is in descending order (ie has been sorted).

We use the cache first to find URL redirects.
-}
consolidateUrls :: [Counter String] -> IO (Sorted URIInfo)
consolidateUrls orig = 
    bracket
    (openLocalStateFrom "simplestats" emptySimpleStatsStore)
    closeAcidState
    (doUrls orig)

doUrls ::
    [Counter String]
    -> AcidState SimpleStatsStore
    -> IO (Sorted  URIInfo)
doUrls orig acid = do
    let ourls = map _value orig 
    new <- mapM (findRedirect acid) ourls
    let ncnts = zipWith (curry replaceUrl) new orig
        ans = foldl' (\omap Counter {..} -> M.insertWith' (+) _value _count omap) M.empty ncnts
    return $ toSortedCL $ map (uncurry Counter) $ M.toList ans
    
{-
Replace a redirected URL. We use a status value of 0 to
indicate a problem.
-}
replaceUrl :: (Maybe URIInfo, Counter String) -> Counter URIInfo
replaceUrl (Nothing,  Counter u c) = 
    let uri = fromMaybe (error ("Invalid URI: " ++ show u)) $ N.parseURI u
    in Counter (URIInfo [0] uri) c
replaceUrl (Just u,   Counter _ c) = Counter u c

displayCount :: 
    QueryResponse
    -> IO ()
displayCount (n, nrtonly, ntws, nrtws, nPub, rtwHist, utwHist, urtwHist, npubHist, _, _, rtStatus, repliedUser, garrulousUser, rtUser, mUser, mHT, mURL, mPub, _, uMap, ftime, ltime) = do
  putStrLn $ ">> Number of tweeters: " ++ show n
  putStrLn $ ">> Number of tweeters that *only* retweeted: " ++ show nrtonly
  putStrLn $ ">> First tweet: " ++ show ftime
  putStrLn $ ">> Last tweet:  " ++ show ltime
  putStrLn $ ">> Number of tweets: " ++ show ntws ++ " Number of retweets: " ++ show nrtws
  putStrLn $ ">> Number of tweets that included a publisher: " ++ show nPub
  putStrLn "*** Most retweeted statuses"
  forM_ (fromCL rtStatus) $ \(Counter obj cnt) -> putStrLn $ show cnt ++ " status=" ++ show obj
  putStrLn "*** Most replied-to user"
  forM_ (fromCL repliedUser) $ \(Counter uid cnt) -> putStrLn $ show cnt ++ " user=" ++ show (M.lookup uid uMap)
  putStrLn "*** Most garrulous user (makes most replies that are not retweets)"
  forM_ (fromCL garrulousUser) $ \(Counter uid cnt) -> putStrLn $ show cnt ++ " user=" ++ show (M.lookup uid uMap)
  putStrLn "*** Most retweeted user"
  forM_ (fromCL rtUser) $ \(Counter uid cnt) -> putStrLn $ show cnt ++ " user=" ++ show (M.lookup uid uMap)
  putStrLn "*** Most mentioned user"
  forM_ (fromCL mUser) $ \(Counter uid cnt) -> putStrLn $ show cnt ++ " user=" ++ show (M.lookup uid uMap)
  putStrLn "*** Most mentioned hashtag"
  forM_ (fromCL mHT) $ \(Counter ht cnt) -> putStrLn $ show cnt ++ " #" ++ ht
  putStrLn "*** Histogram of number of retweets of a tweet"
  forM_ rtwHist $ \(k,v) -> when (v > 0) (putStrLn $ "Num retweets = " ++ show k ++ " " ++ show v ++ " times")
  putStrLn "*** Histogram of number of tweets"
  forM_ utwHist $ \(k,v) -> when (v > 0) (putStrLn $ "Num tweets = " ++ show k ++ " " ++ show v ++ " times")
  putStrLn "*** Histogram of number of retweets by a user"
  forM_ urtwHist $ \(k,v) -> when (v > 0) (putStrLn $ "Num tweets = " ++ show k ++ " " ++ show v ++ " times")
  putStrLn "*** Histogram of number of publishers by a user"
  forM_ npubHist $ \(k,v) -> when (v > 0) (putStrLn $ "Num publishers = " ++ show k ++ " " ++ show v ++ " times")
  putStrLn "*** Most mentioned URL"
  forM_ (fromCL mURL) $ \(Counter u cnt) -> putStrLn $ show cnt ++ " <" ++ show u ++ ">"
  putStrLn "*** Most used publisher"
  forM_ (fromCL mPub) $ \(Counter p cnt) -> putStrLn $ show cnt ++ " " ++ T.unpack p

-- | Replace the id of a user with a human-readable label
replaceUserId :: M.Map UserId BasicUserInfo -> Counter UserId -> Counter String
replaceUserId uMap (Counter uid c) = 
    let f bui = let ustr = "@" ++ 
                           T.unpack (getUserHandle bui) ++
                           " (" ++ T.unpack (getUserName bui) ++ ")"
                in Counter ustr c
    in maybe (error "Unable to find user id") f $ M.lookup uid uMap

displayAsJSON ::
    QueryResponse
    -> IO ()
displayAsJSON ( n, nrtonly, ntws, nrtws, nWithPub
              , rtwHist, utwHist, urtwHist, nPubHist
              , rtwDelta10MinHist, rtwDelta6HourHist, rtStatus, repliedUser, garrulousUser, rtUser, mUser, mHT, mURL, mPub, friendCount, uMap, fTime, lTime) = do
  let fixUser = map (replaceUserId uMap) . fromCL

      toF (nfr,nfoll,nt,nrt) = object [ "follow" .= nfr
                                      , "followers" .= nfoll
                                      , "ntweets" .= nt
                                      , "nretweets" .= nrt
                                      ]

      obj = object [ "numTweeters" .= n
                   , "numOnlyRetweet" .= nrtonly
                   , "firstTweet" .= fTime
                   , "lastTweet" .= lTime 
                   , "numTweets" .= ntws
                   , "numReTweets" .= nrtws
                   , "repliedUsers"   .= fixUser repliedUser
                   , "garrulousUsers" .= fixUser garrulousUser
                   , "retweetedUsers" .= fixUser rtUser
                   , "mentionedUsers" .= fixUser mUser
                   , "mostRetweeted" .= fromCL rtStatus
                   , "retweetHist" .= rtwHist
                   , "userTweetHist" .= utwHist
                   , "userRetweetHist" .= urtwHist
                   , "numPubHist" .= nPubHist
                   , "retweetDeltaHist10Min" .= rtwDelta10MinHist
                   , "retweetDeltaHist6Hour" .= rtwDelta6HourHist
                   , "uris" .= fromCL mURL
                   , "hashtag" .= fromCL mHT
                   , "publisher" .= fromCL mPub
                   , "numWithPublisher" .= nWithPub
                   , "followerCount" .= map toF friendCount
                   ]

  LB.putStrLn . encode . toJSON $ obj

usage :: IO ()
usage = do
  pName <- getProgName
  logIt $ "Usage: " ++ pName ++ " [json] <endpoint> <nvals>"
  exitFailure

main :: IO ()
main = do
  args <- getArgs
  case args of
    (a1:a2:[]) -> case a1 of
      "json" -> usage
      _ -> case maybeRead a2 of
        Just i -> querySPARQL a1 i >>= displayCount
        _ -> usage
        
    (b1:b2:b3:[]) -> case b1 of
      "json" -> case maybeRead b3 of
        Nothing -> usage
        Just j -> querySPARQL b2 j >>= displayAsJSON
        
      _ -> usage
      
    _ -> usage