From 323474c97ee4adc2b905c3c754f7a137e06d1e81 Mon Sep 17 00:00:00 2001
From: Eugen Rochko <eugen@zeonfederated.com>
Date: Thu, 17 Mar 2016 11:59:18 +0100
Subject: [PATCH] Fix #2, add rake task for PuSH-unsubscribing from remote
 users who have no local followers. Remote users' usernames SHOULD be
 case-sensitive

---
 app/controllers/api/accounts_controller.rb |  9 +++++++--
 app/models/account.rb                      |  3 ++-
 lib/tasks/subscriptions.rake               | 13 +++++++++++++
 3 files changed, 22 insertions(+), 3 deletions(-)
 create mode 100644 lib/tasks/subscriptions.rake

diff --git a/app/controllers/api/accounts_controller.rb b/app/controllers/api/accounts_controller.rb
index 13c2b3d8a..782cc8102 100644
--- a/app/controllers/api/accounts_controller.rb
+++ b/app/controllers/api/accounts_controller.rb
@@ -19,12 +19,17 @@ class Api::AccountsController < ApiController
   end
 
   def follow
-    @follow = current_user.account.follow!(@account)
+    if @account.local?
+      @follow = current_user.account.follow!(@account)
+    else
+      @follow = FollowService.new.(current_user.account, @account.acct)
+    end
+
     render action: :show
   end
 
   def unfollow
-    @unfollow = current_user.account.unfollow!(@account)
+    @unfollow = UnfollowService.new.(current_user.account, @account)
     render action: :show
   end
 
diff --git a/app/models/account.rb b/app/models/account.rb
index 524d05f86..e4295d735 100644
--- a/app/models/account.rb
+++ b/app/models/account.rb
@@ -1,7 +1,8 @@
 class Account < ActiveRecord::Base
   # Local users
   has_one :user, inverse_of: :account
-  validates :username, uniqueness: { scope: :domain, case_sensitive: false }
+  validates :username, uniqueness: { scope: :domain, case_sensitive: false }, if:     'local?'
+  validates :username, uniqueness: { scope: :domain, case_sensitive: true },  unless: 'local?'
 
   # Avatar upload
   attr_reader :avatar_remote_url
diff --git a/lib/tasks/subscriptions.rake b/lib/tasks/subscriptions.rake
new file mode 100644
index 000000000..875bd8ae6
--- /dev/null
+++ b/lib/tasks/subscriptions.rake
@@ -0,0 +1,13 @@
+namespace :subscriptions do
+
+  desc "For all remote accounts that have no local followers, unsubscribe from PuSH"
+  task clear: :environment do
+    accounts = Account.where('(select count(f.id) from follows as f where f.target_account_id = accounts.id) = 0').where.not(domain: nil)
+
+    accounts.each do |a|
+      a.subscription(api_subscription_url(a.id)).unsubscribe
+      a.update!(verify_token: '', secret: '')
+    end
+  end
+
+end