<commit_before>/*
 * Copyright 2012 Proletariat Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <DeprecatedHeaders/Facebook.h>
#include "Facebook.h"
#include "FBEvent.h"

namespace nme {
  void PauseAnimation();
  void ResumeAnimation();
}

extern "C" void facebook_send_event(FBEvent &event);
extern "C" void facebook_send_callback(const char *tId, const char *data, const char *error);
@interface NMEAppDelegate : NSObject <UIApplicationDelegate>
{
  UIWindow *window;
  UIViewController *controller;
  BOOL isRunning;
  BOOL isPaused;
}
@end

@interface NMEAppDelegate (FacebookExtensions)
  - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation;
@end

@implementation NMEAppDelegate (FacebookExtensions)
  // TODO do not use a category here. This is dangerous if you have multiple categories for UIApplicationDelegate with openURL defined
  - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  {
    printf("Facebook.mm::openURL\n");
    return [FBSession.activeSession handleOpenURL:url];
  }
@end

@interface FacebookAppDelegate:NSObject
  - (void)applicationActivated:(id)sender;
  -(void)applicationWillTerminate:(id)sender;
@end

@implementation FacebookAppDelegate
  - (id)init {
    self = [super init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationActivated:)
      name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:)
      name:UIApplicationWillTerminateNotification object:nil];
    return self;
  }

  - (void)applicationActivated:(id)sender {
    printf("Facebook.mm::applicationDidBecomeActive\n");
    [[FBSession activeSession] handleDidBecomeActive];
  }

  -(void)applicationWillTerminate:(id)sender {
    printf("Facebook.mm::applicationWillTerminate\n");
    [[FBSession activeSession] close];
  }

  - (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
  }
@end

@interface InviteDialogDelegate : NSObject <FBDialogDelegate>
{
  const char *transactionId;
}
@end

@implementation InviteDialogDelegate
  - (id)init:(const char *)tid {
    self = [super init];
    if (self) {
      transactionId = tid;
    }
    return self;
  }

  - (void) dialogCompleteWithUrl:(NSURL *)url {
    facebook_send_callback(transactionId, "", "");
  }

  - (void ) dialogDidComplete:(FBDialog *)dialog {
    nme::ResumeAnimation();
  }

  - (void)dealloc {
    [super dealloc];
  }
@end

@interface FeedDialogDelegate : NSObject <FBDialogDelegate>
{
  const char *transactionId;
}
@end

@implementation FeedDialogDelegate
  - (id)init:(const char *)tid {
    self = [super init];
    if (self) {
      transactionId = tid;
    }
    return self;
  }

  - (void)dialogDidComplete:(FBDialog *)dialog {
    facebook_send_callback(transactionId, "", "");
    nme::ResumeAnimation();
  }

  - (void)dialogDidNotComplete:(FBDialog *)dialog {
    nme::ResumeAnimation();
  }

  - (void)dealloc {
    [super dealloc];
  }
@end

namespace facebook
{
  Facebook *facebook;
  static bool haveRequestedPublishPermissions = false;
  static bool startingSession = false;
  FacebookAppDelegate *nmeAppActivator;

  void init(const char *i_appId);
  void startSession();
  void closeSession();
  bool sessionActive();
  void requestWritePermissions();
  void requestForMe();
  void graphRequest(const char *transactionId, const char *i_graphPath, const char *i_httpMethod,
      const char *i_paramsJSON);
  void invite(const char *transactionId, const char *i_msg);
  void feedPost(const char *transactionId, const char *i_paramsJSON);
  void dispatchHaxeEvent(EventType eventId);
  void checkForOAuthError(NSError *error);

  void init(const char *i_appId) {
    NSString *appId = [[NSString alloc] initWithUTF8String:i_appId];
    [FBSession setDefaultAppID:appId];
    facebook = [[Facebook alloc] initWithAppId:appId andDelegate:nil];
    [facebook retain];
    nmeAppActivator = [[FacebookAppDelegate alloc]init];
    [nmeAppActivator retain];
  }

  void startSession() {
    if ( !startingSession ) {
      startingSession = true;
      @try {
        [FBSession openActiveSessionWithReadPermissions:nil allowLoginUI:YES
          completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
            if (!error) {
              switch (status) {
                case FBSessionStateOpen:
                  facebook.accessToken = [FBSession activeSession].accessToken;
                  facebook.expirationDate = [FBSession activeSession].expirationDate;
                  dispatchHaxeEvent(START_SESSION_OPEN);
                  break;
                case FBSessionStateClosed:
                case FBSessionStateClosedLoginFailed:
                  closeSession();<commit_msg>Guard openURL to ensure facebook is initialized first<commit_after>/*
 * Copyright 2012 Proletariat Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <DeprecatedHeaders/Facebook.h>
#include "Facebook.h"
#include "FBEvent.h"

namespace nme {
  void PauseAnimation();
  void ResumeAnimation();
}

namespace facebook {
  static bool sessionStarted = false;
}

extern "C" void facebook_send_event(FBEvent &event);
extern "C" void facebook_send_callback(const char *tId, const char *data, const char *error);
@interface NMEAppDelegate : NSObject <UIApplicationDelegate>
{
  UIWindow *window;
  UIViewController *controller;
  BOOL isRunning;
  BOOL isPaused;
}
@end

@interface NMEAppDelegate (FacebookExtensions)
  - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation;
@end

@implementation NMEAppDelegate (FacebookExtensions)
  // TODO do not use a category here. This is dangerous if you have multiple categories for UIApplicationDelegate with openURL defined
  - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  {
    printf("Facebook.mm::openURL\n");
    if ( facebook::sessionStarted ) {
      return [FBSession.activeSession handleOpenURL:url];
    } else {
      return NO;
    }
  }
@end

@interface FacebookAppDelegate:NSObject
  - (void)applicationActivated:(id)sender;
  -(void)applicationWillTerminate:(id)sender;
@end

@implementation FacebookAppDelegate
  - (id)init {
    self = [super init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationActivated:)
      name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:)
      name:UIApplicationWillTerminateNotification object:nil];
    return self;
  }

  - (void)applicationActivated:(id)sender {
    printf("Facebook.mm::applicationDidBecomeActive\n");
    [[FBSession activeSession] handleDidBecomeActive];
  }

  -(void)applicationWillTerminate:(id)sender {
    printf("Facebook.mm::applicationWillTerminate\n");
    [[FBSession activeSession] close];
  }

  - (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
  }
@end

@interface InviteDialogDelegate : NSObject <FBDialogDelegate>
{
  const char *transactionId;
}
@end

@implementation InviteDialogDelegate
  - (id)init:(const char *)tid {
    self = [super init];
    if (self) {
      transactionId = tid;
    }
    return self;
  }

  - (void) dialogCompleteWithUrl:(NSURL *)url {
    facebook_send_callback(transactionId, "", "");
  }

  - (void ) dialogDidComplete:(FBDialog *)dialog {
    nme::ResumeAnimation();
  }

  - (void)dealloc {
    [super dealloc];
  }
@end

@interface FeedDialogDelegate : NSObject <FBDialogDelegate>
{
  const char *transactionId;
}
@end

@implementation FeedDialogDelegate
  - (id)init:(const char *)tid {
    self = [super init];
    if (self) {
      transactionId = tid;
    }
    return self;
  }

  - (void)dialogDidComplete:(FBDialog *)dialog {
    facebook_send_callback(transactionId, "", "");
    nme::ResumeAnimation();
  }

  - (void)dialogDidNotComplete:(FBDialog *)dialog {
    nme::ResumeAnimation();
  }

  - (void)dealloc {
    [super dealloc];
  }
@end

namespace facebook
{
  Facebook *facebook;
  static bool haveRequestedPublishPermissions = false;
  static bool startingSession = false;
  FacebookAppDelegate *nmeAppActivator;

  void init(const char *i_appId);
  void startSession();
  void closeSession();
  bool sessionActive();
  void requestWritePermissions();
  void requestForMe();
  void graphRequest(const char *transactionId, const char *i_graphPath, const char *i_httpMethod,
      const char *i_paramsJSON);
  void invite(const char *transactionId, const char *i_msg);
  void feedPost(const char *transactionId, const char *i_paramsJSON);
  void dispatchHaxeEvent(EventType eventId);
  void checkForOAuthError(NSError *error);

  void init(const char *i_appId) {
    NSString *appId = [[NSString alloc] initWithUTF8String:i_appId];
    [FBSession setDefaultAppID:appId];
    facebook = [[Facebook alloc] initWithAppId:appId andDelegate:nil];
    [facebook retain];
    nmeAppActivator = [[FacebookAppDelegate alloc]init];
    [nmeAppActivator retain];
  }

  void startSession() {
    if ( !startingSession ) {
      startingSession = true;
      @try {
        [FBSession openActiveSessionWithReadPermissions:nil allowLoginUI:YES
          completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
            if (!error) {
              switch (status) {
                case FBSessionStateOpen:
                  facebook.accessToken = [FBSession activeSession].accessToken;
                  facebook.expirationDate = [FBSession activeSession].expirationDate;
                  sessionStarted = true;
                  dispatchHaxeEvent(START_SESSION_OPEN);
                  break;
                case FBSessionStateClosed:
                case FBSessionStateClosedLoginFailed:
                  closeSession();
{'fraction_non_alphanumeric': 0.10178682549559961, 'fraction_numerical': 0.0016001422348653213, 'mean_word_length': 4.127620783956244, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 26, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5660612', 'n_tokens_mistral': 3312, 'n_tokens_neox': 3149, 'n_words': 817}