CCMain.m 221 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225
  1. //
  2. // CCMain.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotos.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "JDStatusBarNotification.h"
  35. #import "NCAutoUpload.h"
  36. #import "NCClientEncryption.h"
  37. #import "NCBridgeSwift.h"
  38. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate, UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, CCLoginDelegate, CCLoginDelegateWeb>
  39. {
  40. tableMetadata *_metadata;
  41. BOOL _isRoot;
  42. BOOL _isViewDidLoad;
  43. BOOL _isSelectedMode;
  44. NSMutableDictionary *_selectedFileIDsMetadatas;
  45. NSUInteger _numSelectedFileIDsMetadatas;
  46. NSMutableArray *_queueSelector;
  47. NSMutableDictionary *_statusSwipeCell;
  48. UIImageView *_ImageTitleHomeCryptoCloud;
  49. UIView *_reMenuBackgroundView;
  50. UITapGestureRecognizer *_singleFingerTap;
  51. NSString *_directoryGroupBy;
  52. NSString *_directoryOrder;
  53. NSUInteger _failedAttempts;
  54. NSDate *_lockUntilDate;
  55. NSString *_fatherPermission;
  56. UIRefreshControl *_refreshControl;
  57. UIDocumentInteractionController *_docController;
  58. CCHud *_hud;
  59. CCHud *_hudDeterminate;
  60. // Datasource
  61. CCSectionDataSourceMetadata *_sectionDataSource;
  62. NSDate *_dateReadDataSource;
  63. // Search
  64. BOOL _isSearchMode;
  65. NSString *_searchFileName;
  66. NSMutableArray *_searchResultMetadatas;
  67. NSString *_noFilesSearchTitle;
  68. NSString *_noFilesSearchDescription;
  69. NSTimer *_timerWaitInput;
  70. // Login
  71. CCLoginWeb *_loginWeb;
  72. CCLogin *_loginVC;
  73. BOOL _loadingFolder;
  74. }
  75. @end
  76. @implementation CCMain
  77. #pragma --------------------------------------------------------------------------------------------
  78. #pragma mark ===== Init =====
  79. #pragma --------------------------------------------------------------------------------------------
  80. - (id)initWithCoder:(NSCoder *)aDecoder
  81. {
  82. if (self = [super initWithCoder:aDecoder]) {
  83. _directoryOrder = [CCUtility getOrderSettings];
  84. _directoryGroupBy = [CCUtility getGroupBySettings];
  85. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  90. }
  91. return self;
  92. }
  93. #pragma --------------------------------------------------------------------------------------------
  94. #pragma mark ===== View =====
  95. #pragma --------------------------------------------------------------------------------------------
  96. - (void)viewDidLoad
  97. {
  98. [super viewDidLoad];
  99. // init object
  100. _metadata = [tableMetadata new];
  101. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  102. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  103. _selectedFileIDsMetadatas = [NSMutableDictionary new];
  104. _statusSwipeCell = [NSMutableDictionary new];
  105. _queueSelector = [NSMutableArray new];
  106. _isViewDidLoad = YES;
  107. _fatherPermission = @"";
  108. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  109. _searchResultMetadatas = [NSMutableArray new];
  110. _searchFileName = @"";
  111. _noFilesSearchTitle = @"";
  112. _noFilesSearchDescription = @"";
  113. // delegate
  114. self.tableView.delegate = self;
  115. self.tableView.tableFooterView = [UIView new];
  116. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  117. self.tableView.emptyDataSetDelegate = self;
  118. self.tableView.emptyDataSetSource = self;
  119. self.searchController.delegate = self;
  120. self.searchController.searchBar.delegate = self;
  121. [CCNetworking sharedNetworking].delegate = self;
  122. // Custom Cell
  123. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  124. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  125. // long press recognizer TableView
  126. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  127. [self.tableView addGestureRecognizer:longPressRecognizer];
  128. // Pull-to-Refresh
  129. [self createRefreshControl];
  130. // Register for 3D Touch Previewing if available
  131. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  132. {
  133. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  134. }
  135. // Back Button
  136. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  137. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  138. // reMenu Background
  139. _reMenuBackgroundView = [[UIView alloc] init];
  140. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  141. // if this is not Main (the Main uses inizializeMain)
  142. if (_isRoot == NO && app.activeAccount.length > 0) {
  143. // Settings this folder & delegate & Loading datasource
  144. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  145. // Load Datasource
  146. [self reloadDatasource:_serverUrl];
  147. // Read (File) Folder
  148. [self readFileReloadFolder];
  149. }
  150. // Title
  151. [self setTitle];
  152. // Search
  153. self.definesPresentationContext = YES;
  154. self.searchController.searchResultsUpdater = self;
  155. self.searchController.dimsBackgroundDuringPresentation = NO;
  156. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  157. [self.searchController.searchBar sizeToFit];
  158. self.searchController.searchBar.delegate = self;
  159. if (@available(iOS 11, *)) {
  160. self.navigationItem.searchController = self.searchController;
  161. self.navigationItem.hidesSearchBarWhenScrolling = true;
  162. self.navigationItem.searchController.searchBar.tintColor = [UIColor whiteColor];
  163. UITextField *textField = [self.searchController.searchBar valueForKey:@"searchField"];
  164. textField.textColor = [UIColor blackColor];
  165. textField.tintColor = [UIColor blackColor];
  166. UIView *backgroundView = textField.subviews.firstObject;
  167. backgroundView.backgroundColor = UIColor.whiteColor;
  168. backgroundView.layer.cornerRadius = 10;
  169. backgroundView.clipsToBounds = YES;
  170. } else {
  171. self.tableView.tableHeaderView = self.searchController.searchBar;
  172. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  173. }
  174. }
  175. // Apparirà
  176. - (void)viewWillAppear:(BOOL)animated
  177. {
  178. [super viewWillAppear:animated];
  179. // test
  180. if (app.activeAccount.length == 0)
  181. return;
  182. // Settings this folder & delegate & Loading datasource
  183. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  184. [CCNetworking sharedNetworking].delegate = self;
  185. // Color
  186. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  187. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  188. if (_isSelectedMode)
  189. [self setUINavigationBarSelected];
  190. else
  191. [self setUINavigationBarDefault];
  192. // If not editing mode remove _selectedFileIDs
  193. if (!self.tableView.editing)
  194. [_selectedFileIDsMetadatas removeAllObjects];
  195. // Plus Button
  196. [app plusButtonVisibile:true];
  197. }
  198. // E' arrivato
  199. - (void)viewDidAppear:(BOOL)animated
  200. {
  201. [super viewDidAppear:animated];
  202. // Active Main
  203. app.activeMain = self;
  204. // Test viewDidLoad
  205. if (_isViewDidLoad) {
  206. _isViewDidLoad = NO;
  207. } else {
  208. if (app.activeAccount.length > 0 && [_selectedFileIDsMetadatas count] == 0) {
  209. // Load Datasource
  210. [self reloadDatasource:_serverUrl];
  211. // Read (file) Folder
  212. [self readFileReloadFolder];
  213. }
  214. }
  215. // Title
  216. [self setTitle];
  217. }
  218. - (void)viewWillDisappear:(BOOL)animated
  219. {
  220. [super viewWillDisappear:animated];
  221. [self closeAllMenu];
  222. }
  223. - (void)didReceiveMemoryWarning
  224. {
  225. [super didReceiveMemoryWarning];
  226. // Dispose of any resources that can be recreated.
  227. }
  228. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  229. {
  230. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  231. [self closeAllMenu];
  232. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  233. if (self.view.frame.size.width == ([[UIScreen mainScreen] bounds].size.width*([[UIScreen mainScreen] bounds].size.width<[[UIScreen mainScreen] bounds].size.height))+([[UIScreen mainScreen] bounds].size.height*([[UIScreen mainScreen] bounds].size.width>[[UIScreen mainScreen] bounds].size.height))) {
  234. // Portrait
  235. } else {
  236. // Landscape
  237. }
  238. [self.tableView reloadData];
  239. }];
  240. }
  241. - (BOOL)prefersStatusBarHidden
  242. {
  243. return NO;
  244. }
  245. // detect scroll for remove keyboard in search mode
  246. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  247. {
  248. if (_isSearchMode && scrollView == self.tableView) {
  249. [self.searchController.searchBar endEditing:YES];
  250. }
  251. }
  252. - (void)changeTheming
  253. {
  254. if (self.isViewLoaded && self.view.window)
  255. [app changeTheming:self];
  256. // Refresh control
  257. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  258. // Reload Table View
  259. [self tableViewReloadData];
  260. }
  261. #pragma --------------------------------------------------------------------------------------------
  262. #pragma mark ===== Initizlize Mail =====
  263. #pragma --------------------------------------------------------------------------------------------
  264. - (void)initializeMain:(NSNotification *)notification
  265. {
  266. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  267. _directoryGroupBy = nil;
  268. _directoryOrder = nil;
  269. _dateReadDataSource = nil;
  270. // test
  271. if (app.activeAccount.length == 0)
  272. return;
  273. if ([app.listMainVC count] == 0 || _isRoot) {
  274. // This is Root home main add list
  275. appDelegate.homeMain = self;
  276. _isRoot = YES;
  277. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  278. appDelegate.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  279. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  280. // go Home
  281. [self.navigationController popToRootViewControllerAnimated:NO];
  282. // setting Networking
  283. [CCNetworking sharedNetworking].delegate = self;
  284. [[CCNetworking sharedNetworking] settingAccount];
  285. // Remove search mode
  286. [self cancelSearchBar];
  287. // populate shared Link & User
  288. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  289. if (results) {
  290. appDelegate.sharesLink = results[0];
  291. appDelegate.sharesUserAndGroup = results[1];
  292. }
  293. // Load Datasource
  294. [self reloadDatasource:_serverUrl];
  295. // Read (File) Folder
  296. [self readFileReloadFolder];
  297. // Setting Theming
  298. [app settingThemingColorBrand];
  299. // Load photo datasorce
  300. if (appDelegate.activePhotos)
  301. [appDelegate.activePhotos reloadDatasourceForced];
  302. // remove all of detail
  303. if (appDelegate.activeDetail)
  304. [appDelegate.activeDetail removeAllView];
  305. // remove all Notification Messages
  306. [appDelegate.listOfNotifications removeAllObjects];
  307. // Not Photos Video in library ? then align
  308. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", app.activeAccount]];
  309. if ([recordsPhotoLibrary count] == 0) {
  310. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  311. }
  312. // Initializations
  313. [appDelegate applicationInitialized];
  314. } else {
  315. // reload datasource
  316. [self reloadDatasource:_serverUrl];
  317. }
  318. }
  319. #pragma --------------------------------------------------------------------------------------------
  320. #pragma mark ==== DZNEmptyDataSetSource ====
  321. #pragma --------------------------------------------------------------------------------------------
  322. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  323. {
  324. if (_loadingFolder)
  325. return NO;
  326. else
  327. return YES;
  328. }
  329. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  330. {
  331. return [UIColor whiteColor];
  332. }
  333. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  334. {
  335. if (_isSearchMode)
  336. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"searchBig"] color:[NCBrandColor sharedInstance].brand];
  337. else
  338. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  339. }
  340. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  341. {
  342. if (_loadingFolder && _refreshControl.isRefreshing == NO) {
  343. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  344. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  345. activityView.color = [NCBrandColor sharedInstance].brand;
  346. [activityView startAnimating];
  347. return activityView;
  348. }
  349. return nil;
  350. }
  351. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  352. {
  353. NSString *text;
  354. if (_isSearchMode) {
  355. text = _noFilesSearchTitle;
  356. } else {
  357. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  358. }
  359. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  360. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  361. }
  362. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  363. {
  364. NSString *text;
  365. if (_isSearchMode) {
  366. text = _noFilesSearchDescription;
  367. } else {
  368. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  369. }
  370. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  371. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  372. paragraph.alignment = NSTextAlignmentCenter;
  373. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  374. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  375. }
  376. #pragma --------------------------------------------------------------------------------------------
  377. #pragma mark ===== Text Field =====
  378. #pragma --------------------------------------------------------------------------------------------
  379. - (void)minCharTextFieldDidChange:(UITextField *)sender
  380. {
  381. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  382. if (alertController)
  383. {
  384. UITextField *fileName = alertController.textFields.firstObject;
  385. UIAlertAction *okAction = alertController.actions.lastObject;
  386. okAction.enabled = fileName.text.length > 0;
  387. }
  388. }
  389. - (void)textFieldDidBeginEditing:(UITextField *)textField{
  390. [textField selectAll:textField];
  391. }
  392. #pragma --------------------------------------------------------------------------------------------
  393. #pragma mark ===== Graphic Window =====
  394. #pragma --------------------------------------------------------------------------------------------
  395. - (void)createRefreshControl
  396. {
  397. _refreshControl = [UIRefreshControl new];
  398. if (@available(iOS 11.0, *)) {
  399. [self.tableView setRefreshControl:_refreshControl];
  400. _refreshControl.tintColor = [UIColor whiteColor];
  401. } else {
  402. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  403. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  404. [self setRefreshControl:_refreshControl];
  405. }
  406. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  407. }
  408. - (void)deleteRefreshControl
  409. {
  410. [_refreshControl endRefreshing];
  411. self.refreshControl = nil;
  412. }
  413. - (void)refreshControlTarget
  414. {
  415. [self readFolder:_serverUrl];
  416. // Actuate `Peek` feedback (weak boom)
  417. AudioServicesPlaySystemSound(1519);
  418. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  419. }
  420. - (void)setTitle
  421. {
  422. // Color text self.navigationItem.title
  423. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  424. if (_isSelectedMode) {
  425. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  426. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  427. self.navigationItem.titleView = nil;
  428. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  429. } else {
  430. // we are in home : LOGO BRAND
  431. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  432. self.navigationItem.title = nil;
  433. if ([app.reachability isReachable] == NO)
  434. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  435. else
  436. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  437. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  438. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo:)];
  439. [singleTap setNumberOfTapsRequired:1];
  440. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  441. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  442. } else {
  443. self.navigationItem.title = _titleMain;
  444. }
  445. }
  446. }
  447. - (void)setUINavigationBarDefault
  448. {
  449. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  450. UIBarButtonItem *buttonMore, *buttonNotification;
  451. // =
  452. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  453. buttonMore.enabled = true;
  454. // <
  455. self.navigationController.navigationBar.hidden = NO;
  456. // Notification
  457. if ([app.listOfNotifications count] > 0) {
  458. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  459. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  460. buttonNotification.enabled = true;
  461. }
  462. if (buttonNotification)
  463. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  464. else
  465. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  466. self.navigationItem.leftBarButtonItem = nil;
  467. }
  468. - (void)setUINavigationBarSelected
  469. {
  470. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  471. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  472. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  473. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  474. self.navigationItem.leftBarButtonItem = leftButton;
  475. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  476. }
  477. - (void)cancelSelect
  478. {
  479. [self tableViewSelect:NO];
  480. [app.reSelectMenu close];
  481. }
  482. - (void)closeAllMenu
  483. {
  484. // close Menu
  485. [app.reSelectMenu close];
  486. [app.reMainMenu close];
  487. // Close Menu Logo
  488. [CCMenuAccount dismissMenu];
  489. }
  490. #pragma --------------------------------------------------------------------------------------------
  491. #pragma mark ===== Document Picker =====
  492. #pragma --------------------------------------------------------------------------------------------
  493. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  494. {
  495. NSLog(@"Cancelled");
  496. }
  497. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  498. {
  499. NSLog(@"Cancelled");
  500. }
  501. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  502. {
  503. documentPicker.delegate = self;
  504. [self presentViewController:documentPicker animated:YES completion:nil];
  505. }
  506. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  507. {
  508. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  509. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  510. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  511. __block NSError *error;
  512. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  513. NSString *fileName = [url lastPathComponent];
  514. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  515. NSData *data = [NSData dataWithContentsOfURL:newURL];
  516. if (data && error == nil) {
  517. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  518. // Upload File
  519. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:serverUrl session:k_upload_session taskStatus: k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  520. } else {
  521. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  522. }
  523. } else {
  524. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  525. }
  526. }];
  527. }
  528. }
  529. - (void)openImportDocumentPicker
  530. {
  531. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  532. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  533. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  534. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  535. documentProviderMenu.delegate = self;
  536. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  537. }
  538. #pragma --------------------------------------------------------------------------------------------
  539. #pragma mark ===== Assets Picker =====
  540. #pragma --------------------------------------------------------------------------------------------
  541. -(void)dismissFormUploadAssets
  542. {
  543. [self reloadDatasource];
  544. }
  545. - (void)openAssetsPickerController
  546. {
  547. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  548. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  549. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  550. //UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil]; // DEPRECATED iOS9
  551. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedInInstancesOfClasses:@[[CTAssetsPickerController class]]];
  552. [app aspectNavigationControllerBar:navBar online:YES hidden:NO];
  553. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  554. dispatch_async(dispatch_get_main_queue(), ^{
  555. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  556. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeBottom];
  557. // init picker
  558. CTAssetsPickerController *picker = [CTAssetsPickerController new];
  559. // set delegate
  560. picker.delegate = self;
  561. // to show selection order
  562. //picker.showsSelectionIndex = YES;
  563. // to present picker as a form sheet in iPad
  564. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  565. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  566. // present picker
  567. [self presentViewController:picker animated:YES completion:nil];
  568. });
  569. }];
  570. }
  571. - (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
  572. {
  573. if (picker.selectedAssets.count > k_pickerControllerMax) {
  574. [app messageNotification:@"_info_" description:@"_limited_dimension_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  575. return NO;
  576. }
  577. return YES;
  578. }
  579. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  580. {
  581. [picker dismissViewControllerAnimated:YES completion:^{
  582. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  583. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:assets cryptated:NO session:k_upload_session delegate:self];
  584. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  585. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  586. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  587. [self presentViewController:navigationController animated:YES completion:nil];
  588. }];
  589. }
  590. // New folder or new photo or video
  591. - (void)returnCreate:(NSInteger)type
  592. {
  593. switch (type) {
  594. case k_returnCreateFolderPlain: {
  595. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  596. NSString *message;
  597. UIAlertController *alertController;
  598. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  599. message = @"/";
  600. } else {
  601. message = [serverUrl lastPathComponent];
  602. }
  603. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  604. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  605. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  606. textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
  607. }];
  608. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  609. NSLog(@"Cancel action");
  610. }];
  611. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  612. UITextField *fileName = alertController.textFields.firstObject;
  613. [self createFolder:fileName.text serverUrl:serverUrl];
  614. }];
  615. okAction.enabled = NO;
  616. [alertController addAction:cancelAction];
  617. [alertController addAction:okAction];
  618. [self presentViewController:alertController animated:YES completion:nil];
  619. }
  620. break;
  621. case k_returnCreateFotoVideoPlain: {
  622. [self openAssetsPickerController];
  623. }
  624. break;
  625. case k_returnCreateFilePlain: {
  626. [self openImportDocumentPicker];
  627. }
  628. break;
  629. case k_returnCreateFotoVideoEncrypted: {
  630. [self openAssetsPickerController];
  631. }
  632. break;
  633. case k_returnCreateFileEncrypted: {
  634. [self openImportDocumentPicker];
  635. }
  636. break;
  637. case k_returnCreateFileText: {
  638. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"NCText" bundle:nil] instantiateViewControllerWithIdentifier:@"NCText"];
  639. navigationController.modalPresentationStyle = UIModalPresentationPageSheet;
  640. [self presentViewController:navigationController animated:YES completion:nil];
  641. }
  642. break;
  643. }
  644. }
  645. #pragma --------------------------------------------------------------------------------------------
  646. #pragma mark ===== Save selected File =====
  647. #pragma --------------------------------------------------------------------------------------------
  648. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  649. {
  650. if (error)
  651. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  652. else
  653. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  654. }
  655. - (void)saveSelectedFiles
  656. {
  657. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  658. return;
  659. NSLog(@"[LOG] Start download selected files ...");
  660. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  661. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  662. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  663. for (tableMetadata *metadata in metadatas) {
  664. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  665. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  666. if (serverUrl)
  667. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  668. }
  669. }
  670. [_hud hideHud];
  671. });
  672. [self tableViewSelect:NO];
  673. }
  674. #pragma --------------------------------------------------------------------------------------------
  675. #pragma mark === Delegate Login ===
  676. #pragma --------------------------------------------------------------------------------------------
  677. - (void)loginSuccess:(NSInteger)loginType
  678. {
  679. [self readFolder:_serverUrl];
  680. }
  681. - (void)loginDisappear
  682. {
  683. app.activeLogin = nil;
  684. }
  685. #pragma mark -
  686. #pragma --------------------------------------------------------------------------------------------
  687. #pragma mark ===== Peek & Pop =====
  688. #pragma --------------------------------------------------------------------------------------------
  689. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  690. {
  691. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  692. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  693. if (metadata.thumbnailExists) {
  694. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  695. if (cell) {
  696. previewingContext.sourceRect = cell.frame;
  697. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  698. vc.delegate = self;
  699. vc.metadata = metadata;
  700. return vc;
  701. }
  702. }
  703. return nil;
  704. }
  705. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  706. {
  707. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  708. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  709. }
  710. #pragma mark -
  711. #pragma --------------------------------------------------------------------------------------------
  712. #pragma mark ==== External Sites ====
  713. #pragma --------------------------------------------------------------------------------------------
  714. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  715. {
  716. [[NCManageDatabase sharedInstance] deleteExternalSites];
  717. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  718. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  719. }
  720. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  721. {
  722. NSString *error = [NSString stringWithFormat:@"Get external site failure error %lu, %@", (long)errorCode, message];
  723. NSLog(@"[LOG] %@", error);
  724. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get External Sites Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  725. }
  726. #pragma --------------------------------------------------------------------------------------------
  727. #pragma mark ==== Activity ====
  728. #pragma --------------------------------------------------------------------------------------------
  729. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  730. {
  731. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  732. // Reload Activity Data Source
  733. [app.activeActivity reloadDatasource];
  734. }
  735. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  736. {
  737. NSString *error = [NSString stringWithFormat:@"Get Activity Server failure error %lu, %@", (long)errorCode, message];
  738. NSLog(@"[LOG] %@", error);
  739. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Activity Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  740. }
  741. #pragma --------------------------------------------------------------------------------------------
  742. #pragma mark ==== Notification ====
  743. #pragma --------------------------------------------------------------------------------------------
  744. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  745. {
  746. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  747. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  748. // Order by date
  749. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  750. OCNotifications *notification1 = obj1, *notification2 = obj2;
  751. return [notification2.date compare: notification1.date];
  752. }];
  753. // verify if listOfNotifications is changed
  754. NSString *old = @"", *new = @"";
  755. for (OCNotifications *notification in listOfNotifications)
  756. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  757. for (OCNotifications *notification in appDelegate.listOfNotifications)
  758. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  759. if (![new isEqualToString:old]) {
  760. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  761. // reload Notification view
  762. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"notificationReloadData" object:nil];
  763. }
  764. // Update NavigationBar
  765. if (!_isSelectedMode) {
  766. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  767. }
  768. });
  769. }
  770. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  771. {
  772. NSString *error = [NSString stringWithFormat:@"Get Notification Server failure error %lu, %@", (long)errorCode, message];
  773. NSLog(@"[LOG] %@", error);
  774. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Notification Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  775. // Update NavigationBar
  776. if (!_isSelectedMode)
  777. [self setUINavigationBarDefault];
  778. }
  779. - (void)viewNotification
  780. {
  781. if ([app.listOfNotifications count] > 0) {
  782. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  783. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  784. [self presentViewController:notificationVC animated:YES completion:nil];
  785. }
  786. }
  787. #pragma --------------------------------------------------------------------------------------------
  788. #pragma mark ==== User Profile ====
  789. #pragma --------------------------------------------------------------------------------------------
  790. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  791. {
  792. NSString *error = [NSString stringWithFormat:@"Get user profile failure error %lu, %@", (long)errorCode, message];
  793. NSLog(@"[LOG] %@", error);
  794. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get user profile Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  795. }
  796. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  797. {
  798. // Update User (+ userProfile.id)
  799. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  800. // Get Account Active
  801. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  802. // Setting App active account
  803. [app settingActiveAccount:account.account activeUrl:account.url activeUser:account.user activeUserID:account.userID activePassword:account.password];
  804. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  805. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  806. //UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]]; DEPRECATED iOS9
  807. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]]]];
  808. if (avatar)
  809. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  810. else
  811. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  812. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeUserProfile" object:nil];
  813. });
  814. }
  815. #pragma --------------------------------------------------------------------------------------------
  816. #pragma mark ==== Capabilities ====
  817. #pragma --------------------------------------------------------------------------------------------
  818. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  819. {
  820. // Unauthorized
  821. if (errorCode == kOCErrorServerUnauthorized)
  822. [app openLoginView:self loginType:loginModifyPasswordUser];
  823. NSString *error = [NSString stringWithFormat:@"Get Capabilities failure error %lu, %@", (long)errorCode, message];
  824. NSLog(@"[LOG] %@", error);
  825. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Capabilities of Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  826. // Change Theming color
  827. [app settingThemingColorBrand];
  828. }
  829. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  830. {
  831. // Update capabilities db
  832. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  833. // ------ THEMING -----------------------------------------------------------------------
  834. // Download Theming Background & Change Theming color
  835. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  836. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  837. //UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]]; DEPRECATED iOS9
  838. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]]]];
  839. if (themingBackground)
  840. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  841. else
  842. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  843. }
  844. dispatch_async(dispatch_get_main_queue(), ^{
  845. [app settingThemingColorBrand];
  846. });
  847. });
  848. // ------ SEARCH ------------------------------------------------------------------------
  849. // Search bar if change version
  850. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  851. [self cancelSearchBar];
  852. }
  853. // ------ GET SERVICE SERVER ------------------------------------------------------------
  854. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  855. // Read External Sites
  856. if (capabilities.isExternalSitesServerEnabled) {
  857. metadataNet.action = actionGetExternalSitesServer;
  858. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  859. }
  860. // Read Share
  861. if (capabilities.isFilesSharingAPIEnabled) {
  862. [app.sharesID removeAllObjects];
  863. metadataNet.action = actionReadShareServer;
  864. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  865. }
  866. // Read Notification
  867. metadataNet.action = actionGetNotificationServer;
  868. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  869. // Read User Profile
  870. metadataNet.action = actionGetUserProfile;
  871. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  872. // Read Activity
  873. metadataNet.action = actionGetActivityServer;
  874. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  875. }
  876. #pragma mark -
  877. #pragma --------------------------------------------------------------------------------------------
  878. #pragma mark ==== Request Server Information ====
  879. #pragma --------------------------------------------------------------------------------------------
  880. - (void)requestServerCapabilities
  881. {
  882. // test
  883. if (app.activeAccount.length == 0)
  884. return;
  885. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  886. metadataNet.action = actionGetCapabilities;
  887. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  888. }
  889. #pragma mark -
  890. #pragma --------------------------------------------------------------------------------------------
  891. #pragma mark ==== Middleware Ping ====
  892. #pragma --------------------------------------------------------------------------------------------
  893. - (void)middlewarePing
  894. {
  895. // test
  896. if (app.activeAccount.length == 0)
  897. return;
  898. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  899. metadataNet.action = actionMiddlewarePing;
  900. metadataNet.serverUrl = [[NCBrandOptions sharedInstance] middlewarePingUrl];
  901. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  902. }
  903. #pragma mark -
  904. #pragma --------------------------------------------------------------------------------------------
  905. #pragma mark ==== Download Thumbnail Delegate ====
  906. #pragma --------------------------------------------------------------------------------------------
  907. - (void)downloadThumbnailFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  908. {
  909. NSLog(@"[LOG] Download Thumbnail Failure error %lu, %@", (long)errorCode, message);
  910. }
  911. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  912. {
  913. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  914. if ([self indexPathIsValid:indexPath]) {
  915. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]])
  916. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  917. }
  918. }
  919. #pragma --------------------------------------------------------------------------------------------
  920. #pragma mark ==== Download ====
  921. #pragma --------------------------------------------------------------------------------------------
  922. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  923. {
  924. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  925. // File do not exists on server, remove in local
  926. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  927. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  928. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  929. if (metadata.directory && serverUrl) {
  930. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  931. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  932. }
  933. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  934. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  935. }
  936. if ([selector isEqualToString:selectorLoadViewImage]) {
  937. dispatch_async(dispatch_get_main_queue(), ^{
  938. // Updating Detail
  939. if (app.activeDetail)
  940. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  941. // Updating Photos
  942. if (app.activePhotos)
  943. [app.activePhotos downloadFileFailure:errorCode];
  944. });
  945. } else {
  946. if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized)
  947. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  948. }
  949. [self reloadDatasource:serverUrl];
  950. }
  951. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  952. {
  953. __block tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  954. if (metadata == nil)
  955. return;
  956. // Download
  957. if ([selector isEqualToString:selectorDownloadFile]) {
  958. [self reloadDatasource:serverUrl];
  959. }
  960. // Synchronized
  961. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  962. [self reloadDatasource:serverUrl];
  963. }
  964. // add Favorite
  965. if ([selector isEqualToString:selectorAddFavorite]) {
  966. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  967. }
  968. // open View File
  969. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  970. [self reloadDatasource:serverUrl];
  971. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  972. selector = selectorOpenIn;
  973. //[self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  974. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  975. selector = selectorOpenIn;
  976. } else {
  977. _metadata = metadata;
  978. if ([self shouldPerformSegue])
  979. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  980. }
  981. }
  982. // Open with...
  983. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  984. [self reloadDatasource:serverUrl];
  985. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  986. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  987. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName]];
  988. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  989. _docController.delegate = self;
  990. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  991. }
  992. // Save to Photo Album
  993. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  994. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  995. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  996. UIImage *image = [UIImage imageWithContentsOfFile:file];
  997. if (image)
  998. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  999. else
  1000. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1001. }
  1002. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1003. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  1004. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileName])) {
  1005. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileName], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1006. } else {
  1007. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1008. }
  1009. }
  1010. [self reloadDatasource:serverUrl];
  1011. }
  1012. // Copy File
  1013. if ([selector isEqualToString:selectorLoadCopy]) {
  1014. [self reloadDatasource:serverUrl];
  1015. [self copyFileToPasteboard:metadata];
  1016. }
  1017. //download file plist
  1018. if ([selector isEqualToString:selectorLoadPlist]) {
  1019. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1020. long countSelectorLoadPlist = 0;
  1021. for (NSOperation *operation in [app.netQueue operations]) {
  1022. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1023. countSelectorLoadPlist++;
  1024. }
  1025. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1026. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:directoryID] && directoryID) {
  1027. dispatch_async(dispatch_get_main_queue(), ^{
  1028. [self reloadDatasource:serverUrl];
  1029. });
  1030. }
  1031. });
  1032. }
  1033. //selectorLoadViewImage
  1034. if ([selector isEqualToString:selectorLoadViewImage]) {
  1035. // Detail
  1036. if (app.activeDetail)
  1037. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1038. // Photos
  1039. if (app.activePhotos)
  1040. [app.activePhotos downloadFileSuccess:metadata];
  1041. [self reloadDatasource:serverUrl];
  1042. }
  1043. // if exists postselector call self with selectorPost
  1044. if ([selectorPost length] > 0)
  1045. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1046. // Auto Download Upload
  1047. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1048. // ONLY BACKGROUND
  1049. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1050. } else {
  1051. // ONLY FOREFROUND
  1052. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1053. }
  1054. }
  1055. - (void)downloadSelectedFilesFolders
  1056. {
  1057. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1058. return;
  1059. NSLog(@"[LOG] Start download selected ...");
  1060. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1061. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1062. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1063. for (tableMetadata *metadata in selectedMetadatas) {
  1064. if (metadata.directory) {
  1065. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1066. if (serverUrl) {
  1067. serverUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  1068. [[CCSynchronize sharedSynchronize] readFolder:serverUrl selector:selectorReadFolderWithDownload];
  1069. }
  1070. } else {
  1071. [[CCSynchronize sharedSynchronize] readFile:metadata selector:selectorReadFileWithDownload];
  1072. }
  1073. }
  1074. [_hud hideHud];
  1075. });
  1076. [self tableViewSelect:NO];
  1077. }
  1078. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1079. {
  1080. }
  1081. #pragma --------------------------------------------------------------------------------------------
  1082. #pragma mark ===== Upload new Photos/Videos =====
  1083. #pragma --------------------------------------------------------------------------------------------
  1084. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1085. {
  1086. // Auto Download Upload
  1087. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll] || [selector isEqualToString:selectorUploadFile]) {
  1088. if ([[NCManageDatabase sharedInstance] getPriorityQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier] > k_priorityAutoUploadStop) {
  1089. // Change priority Auto Upload
  1090. if ([[NCManageDatabase sharedInstance] setPriorityQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier priority:k_priorityAutoUploadError]) {
  1091. // Activity
  1092. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:message type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  1093. }
  1094. if (errorCode != kCFURLErrorCancelled)
  1095. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1096. } else {
  1097. // Delete record on Table Auto Upload
  1098. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier selector:selector];
  1099. // Activity
  1100. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:@"Too many error, file deleted" type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  1101. [app messageNotification:@"_upload_file_" description:@"Too many error, file deleted, see Activity for more info" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1102. }
  1103. } else {
  1104. // Read File test do not exists
  1105. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1106. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1107. // reUpload
  1108. if (metadata)
  1109. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1110. }
  1111. // Print error
  1112. else if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized) {
  1113. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1114. }
  1115. }
  1116. [self reloadDatasource:serverUrl];
  1117. }
  1118. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1119. {
  1120. // Auto Download Upload
  1121. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1122. // ONLY BACKGROUND
  1123. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1124. } else {
  1125. // ONLY FOREFROUND
  1126. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1127. }
  1128. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1129. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1130. [self readFolder:serverUrl];
  1131. } else {
  1132. [self reloadDatasource:serverUrl];
  1133. }
  1134. });
  1135. }
  1136. //
  1137. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1138. //
  1139. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1140. {
  1141. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1142. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1143. });
  1144. }
  1145. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1146. {
  1147. NSArray *assets = [arguments objectAtIndex:0];
  1148. NSString *serverUrl = [arguments objectAtIndex:1];
  1149. BOOL useSubFolder = [[arguments objectAtIndex:2] boolValue];
  1150. NSString *session = [arguments objectAtIndex:3];
  1151. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  1152. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1153. if (!directoryID) return;
  1154. // if request create the folder for Photos & the subfolders
  1155. if ([autoUploadPath isEqualToString:serverUrl])
  1156. if (![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  1157. return;
  1158. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1159. for (PHAsset *asset in assets) {
  1160. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType];
  1161. NSDate *assetDate = asset.creationDate;
  1162. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1163. // Create serverUrl if use sub folder
  1164. if (useSubFolder) {
  1165. [formatter setDateFormat:@"yyyy"];
  1166. NSString *yearString = [formatter stringFromDate:assetDate];
  1167. [formatter setDateFormat:@"MM"];
  1168. NSString *monthString = [formatter stringFromDate:assetDate];
  1169. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  1170. }
  1171. // Check if is in upload
  1172. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1173. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1174. if ([isRecordInSessions count] > 0) {
  1175. // next upload
  1176. continue;
  1177. } else {
  1178. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1179. metadataNet.action = actionReadFile;
  1180. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1181. metadataNet.fileName = fileName;
  1182. metadataNet.session = session;
  1183. metadataNet.selector = selectorReadFileUploadFile;
  1184. metadataNet.serverUrl = serverUrl;
  1185. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1186. }
  1187. }
  1188. }
  1189. #pragma --------------------------------------------------------------------------------------------
  1190. #pragma mark ==== Read File ====
  1191. #pragma --------------------------------------------------------------------------------------------
  1192. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1193. {
  1194. // Unauthorized
  1195. if (errorCode == kOCErrorServerUnauthorized)
  1196. [app openLoginView:self loginType:loginModifyPasswordUser];
  1197. // UploadFile
  1198. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1199. // File not exists
  1200. if (errorCode == 404) {
  1201. metadataNet.errorCode = 0;
  1202. metadataNet.selector = selectorUploadFile;
  1203. metadataNet.selectorPost = nil;
  1204. metadataNet.taskStatus = k_taskStatusResume;
  1205. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1206. } else {
  1207. // error ho many retry befor notification and go to on next asses
  1208. if (metadataNet.errorRetry < 3) {
  1209. // Retry read file
  1210. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1211. } else {
  1212. // STOP check file, view message error
  1213. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1214. }
  1215. }
  1216. }
  1217. }
  1218. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1219. {
  1220. // Read Folder
  1221. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1222. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", metadataNet.account, metadataNet.serverUrl]];
  1223. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1224. [self readFolder:metadataNet.serverUrl];
  1225. }
  1226. }
  1227. // UploadFile
  1228. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1229. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1230. metadataNet.selector = selectorUploadFile;
  1231. metadataNet.selectorPost = nil;
  1232. metadataNet.taskStatus = k_taskStatusResume;
  1233. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1234. }
  1235. }
  1236. - (void)readFileReloadFolder
  1237. {
  1238. if (!_serverUrl || !app.activeAccount || app.maintenanceMode)
  1239. return;
  1240. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1241. metadataNet.action = actionReadFile;
  1242. metadataNet.priority = NSOperationQueuePriorityHigh;
  1243. metadataNet.selector = selectorReadFileReloadFolder;
  1244. metadataNet.serverUrl = _serverUrl;
  1245. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1246. }
  1247. #pragma --------------------------------------------------------------------------------------------
  1248. #pragma mark ==== Read Folder ====
  1249. #pragma --------------------------------------------------------------------------------------------
  1250. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1251. {
  1252. // stoprefresh
  1253. [_refreshControl endRefreshing];
  1254. // Unauthorized
  1255. if (errorCode == kOCErrorServerUnauthorized)
  1256. [app openLoginView:self loginType:loginModifyPasswordUser];
  1257. _loadingFolder = NO;
  1258. [self tableViewReloadData];
  1259. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1260. // verify active user
  1261. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1262. if (message && [record.account isEqualToString:metadataNet.account])
  1263. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1264. [self reloadDatasource:metadataNet.serverUrl];
  1265. }
  1266. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  1267. {
  1268. // stoprefresh
  1269. [_refreshControl endRefreshing];
  1270. // verify active user
  1271. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1272. if (![record.account isEqualToString:metadataNet.account])
  1273. return;
  1274. // save father e update permission
  1275. if(!_isSearchMode && metadataFolder)
  1276. _fatherPermission = metadataFolder.permissions;
  1277. NSArray *recordsInSessions;
  1278. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1279. if (_isSearchMode) {
  1280. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1281. } else {
  1282. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag];
  1283. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1284. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1285. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1286. }
  1287. for (tableMetadata *metadata in metadatas) {
  1288. // verify if the record is in download/upload progress
  1289. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1290. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1291. // is in Download or Upload
  1292. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1293. continue;
  1294. }
  1295. }
  1296. // Insert in Array
  1297. [metadatasToInsertInDB addObject:metadata];
  1298. }
  1299. // insert in Database
  1300. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl];
  1301. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1302. // read plist
  1303. if (!_isSearchMode)
  1304. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1305. // File is changed ??
  1306. if (!_isSearchMode && metadatasToInsertInDB)
  1307. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1308. });
  1309. // Search Mode
  1310. if (_isSearchMode) {
  1311. // Fix managed -> Unmanaged _searchResultMetadatas
  1312. if (metadatasToInsertInDB)
  1313. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1314. [self reloadDatasource:metadataNet.serverUrl];
  1315. }
  1316. // this is the same directory
  1317. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1318. // reload
  1319. [self reloadDatasource:metadataNet.serverUrl];
  1320. // Enable change user
  1321. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1322. _loadingFolder = NO;
  1323. [self tableViewReloadData];
  1324. }
  1325. }
  1326. - (void)readFolder:(NSString *)serverUrl
  1327. {
  1328. // init control
  1329. if (!serverUrl || !app.activeAccount || app.maintenanceMode) {
  1330. [_refreshControl endRefreshing];
  1331. return;
  1332. }
  1333. // Search Mode
  1334. if (_isSearchMode) {
  1335. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1336. _searchFileName = @""; // forced reload searchg
  1337. [self updateSearchResultsForSearchController:self.searchController];
  1338. return;
  1339. }
  1340. _loadingFolder = YES;
  1341. [self tableViewReloadData];
  1342. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  1343. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1344. metadataNet.action = actionReadFolder;
  1345. metadataNet.date = [NSDate date];
  1346. metadataNet.depth = @"1";
  1347. metadataNet.directoryID = directory.directoryID;
  1348. metadataNet.priority = NSOperationQueuePriorityHigh;
  1349. metadataNet.selector = selectorReadFolder;
  1350. metadataNet.serverUrl = serverUrl;
  1351. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1352. }
  1353. #pragma mark -
  1354. #pragma --------------------------------------------------------------------------------------------
  1355. #pragma mark ===== Search =====
  1356. #pragma --------------------------------------------------------------------------------------------
  1357. -(void)searchStartTimer
  1358. {
  1359. NSString *home = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  1360. [[CCActions sharedInstance] search:home fileName:_searchFileName depth:@"infinity" date:nil selector:selectorSearch delegate:self];
  1361. _noFilesSearchTitle = @"";
  1362. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1363. [self.tableView reloadEmptyDataSet];
  1364. }
  1365. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1366. {
  1367. //[self setNeedsStatusBarAppearanceUpdate];
  1368. _isSearchMode = YES;
  1369. [self deleteRefreshControl];
  1370. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1371. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1372. _searchFileName = fileName;
  1373. // First : filter
  1374. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1375. if (!directoryID) return;
  1376. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileName CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1377. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1378. [_searchResultMetadatas removeAllObjects];
  1379. for (tableMetadata *record in records)
  1380. [_searchResultMetadatas addObject:record];
  1381. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1382. metadataNet.account = app.activeAccount;
  1383. metadataNet.directoryID = directoryID;
  1384. metadataNet.selector = selectorSearch;
  1385. metadataNet.serverUrl = _serverUrl;
  1386. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas];
  1387. // Version >= 12
  1388. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1389. [_timerWaitInput invalidate];
  1390. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1391. }
  1392. }
  1393. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1394. [self reloadDatasource];
  1395. }
  1396. }
  1397. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1398. {
  1399. [self cancelSearchBar];
  1400. [self readFolder:_serverUrl];
  1401. }
  1402. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1403. {
  1404. // Unauthorized
  1405. if (errorCode == kOCErrorServerUnauthorized)
  1406. [app openLoginView:self loginType:loginModifyPasswordUser];
  1407. if (message && errorCode != kOCErrorServerUnauthorized)
  1408. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1409. _searchFileName = @"";
  1410. }
  1411. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1412. {
  1413. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1414. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:metadatas];
  1415. }
  1416. - (void)cancelSearchBar
  1417. {
  1418. if (self.searchController.active) {
  1419. [self.searchController setActive:NO];
  1420. [self createRefreshControl];
  1421. _isSearchMode = NO;
  1422. _searchFileName = @"";
  1423. _dateReadDataSource = nil;
  1424. _searchResultMetadatas = [NSMutableArray new];
  1425. [self reloadDatasource];
  1426. }
  1427. //[self setNeedsStatusBarAppearanceUpdate];
  1428. }
  1429. #pragma mark -
  1430. #pragma --------------------------------------------------------------------------------------------
  1431. #pragma mark ===== Delete File or Folder =====
  1432. #pragma --------------------------------------------------------------------------------------------
  1433. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1434. {
  1435. // Unauthorized
  1436. if (errorCode == kOCErrorServerUnauthorized)
  1437. [app openLoginView:self loginType:loginModifyPasswordUser];
  1438. NSLog(@"[LOG] Delete File failure error %lu, %@", (long)errorCode, message);
  1439. [self deleteFileOrFolderSuccess:metadataNet];
  1440. }
  1441. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1442. {
  1443. [_queueSelector removeObject:metadataNet.selector];
  1444. if ([_queueSelector count] == 0) {
  1445. [_hud hideHud];
  1446. // next
  1447. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1448. if ([_selectedFileIDsMetadatas count] > 0) {
  1449. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1450. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1451. } else {
  1452. // End Select Table View
  1453. [self tableViewSelect:NO];
  1454. // Reload
  1455. if (_isSearchMode)
  1456. [self readFolder:metadataNet.serverUrl];
  1457. else
  1458. [self reloadDatasource:metadataNet.serverUrl];
  1459. }
  1460. }
  1461. }
  1462. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1463. {
  1464. [_queueSelector addObject:selectorDelete];
  1465. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1466. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1467. }
  1468. - (void)deleteFile
  1469. {
  1470. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1471. return;
  1472. [_queueSelector removeAllObjects];
  1473. if ([_selectedFileIDsMetadatas count] > 0) {
  1474. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1475. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1476. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1477. } else {
  1478. _numSelectedFileIDsMetadatas = 1;
  1479. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1480. }
  1481. }
  1482. #pragma --------------------------------------------------------------------------------------------
  1483. #pragma mark ===== Rename / Move =====
  1484. #pragma --------------------------------------------------------------------------------------------
  1485. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1486. {
  1487. [self readFolder:metadataNet.serverUrl];
  1488. }
  1489. - (void)renameFile:(NSArray *)arguments
  1490. {
  1491. tableMetadata* metadata = [arguments objectAtIndex:0];
  1492. NSString *fileName = [arguments objectAtIndex:1];
  1493. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1494. }
  1495. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1496. {
  1497. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1498. [_hud hideHud];
  1499. if (message && errorCode != kOCErrorServerUnauthorized)
  1500. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1501. // End Select Table View
  1502. [self tableViewSelect:NO];
  1503. // reload Datasource
  1504. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1505. [self readFolder:metadataNet.serverUrl];
  1506. else
  1507. [self reloadDatasource];
  1508. }
  1509. }
  1510. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1511. {
  1512. [_queueSelector removeObject:metadataNet.selector];
  1513. if ([_queueSelector count] == 0) {
  1514. [_hud hideHud];
  1515. NSString *fileName = metadataNet.fileName;
  1516. NSString *directoryID = metadataNet.directoryID;
  1517. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1518. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1519. if (!serverUrlTo) return;
  1520. // FILE -> Metadata
  1521. if (metadataNet.directory == NO)
  1522. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1523. // DIRECTORY -> Directory - CCMetadata
  1524. if (metadataNet.directory == YES) {
  1525. // delete all dir / subdir
  1526. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1527. // move metadata
  1528. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1529. // Add new directory
  1530. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1531. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil];
  1532. }
  1533. // next
  1534. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1535. if ([_selectedFileIDsMetadatas count] > 0) {
  1536. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1537. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1538. } else {
  1539. // End Select Table View
  1540. [self tableViewSelect:NO];
  1541. // reload Datasource
  1542. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1543. [self readFolder:metadataNet.serverUrl];
  1544. else
  1545. [self reloadDatasource];
  1546. }
  1547. }
  1548. }
  1549. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1550. {
  1551. tableMetadata *metadata = [arguments objectAtIndex:0];
  1552. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1553. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1554. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1555. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1556. if (!serverUrl) return;
  1557. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1558. if (!directoryIDTo) return;
  1559. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withUserID:app.activeUserID withPassword:app.activePassword withUrl:app.activeUrl];
  1560. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1561. if(!error) {
  1562. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1563. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1564. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1565. }];
  1566. [alert addAction:ok];
  1567. [self presentViewController:alert animated:YES completion:nil];
  1568. });
  1569. // End Select Table View
  1570. [self tableViewSelect:NO];
  1571. // reload Datasource
  1572. [self readFileReloadFolder];
  1573. return;
  1574. }
  1575. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1576. metadataNet.action = actionMoveFileOrFolder;
  1577. metadataNet.directory = metadata.directory;
  1578. metadataNet.fileID = metadata.fileID;
  1579. metadataNet.directoryID = metadata.directoryID;
  1580. metadataNet.directoryIDTo = directoryIDTo;
  1581. metadataNet.fileName = metadata.fileName;
  1582. metadataNet.fileNameTo = metadata.fileName;
  1583. metadataNet.etag = metadata.etag;
  1584. metadataNet.selector = selectorMove;
  1585. metadataNet.serverUrl = serverUrl;
  1586. metadataNet.serverUrlTo = serverUrlTo;
  1587. [_queueSelector addObject:metadataNet.selector];
  1588. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1589. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1590. }
  1591. // DELEGATE : Move
  1592. - (void)dismissMove
  1593. {
  1594. [self reloadDatasource];
  1595. }
  1596. // DELEGATE : Move
  1597. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1598. {
  1599. [_queueSelector removeAllObjects];
  1600. if ([_selectedFileIDsMetadatas count] > 0) {
  1601. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1602. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1603. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1604. } else {
  1605. _numSelectedFileIDsMetadatas = 1;
  1606. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1607. }
  1608. }
  1609. - (void)moveOpenWindow:(NSArray *)indexPaths
  1610. {
  1611. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1612. return;
  1613. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1614. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1615. viewController.delegate = self;
  1616. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1617. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1618. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1619. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1620. viewController.networkingOperationQueue = app.netQueue;
  1621. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1622. [self presentViewController:navigationController animated:YES completion:nil];
  1623. }
  1624. #pragma --------------------------------------------------------------------------------------------
  1625. #pragma mark ===== Create folder =====
  1626. #pragma --------------------------------------------------------------------------------------------
  1627. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1628. {
  1629. // Unauthorized
  1630. if (errorCode == kOCErrorServerUnauthorized)
  1631. [app openLoginView:self loginType:loginModifyPasswordUser];
  1632. if (message && errorCode != kOCErrorServerUnauthorized)
  1633. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1634. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID] clearDateReadDirectoryID:nil];
  1635. [self reloadDatasource];
  1636. // We are in directory fail ?
  1637. CCMain *vc = [app.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:metadataNet.fileName]];
  1638. if (vc)
  1639. [vc.navigationController popViewControllerAnimated:YES];
  1640. }
  1641. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1642. {
  1643. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1644. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil];
  1645. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID]];
  1646. if (metadata) {
  1647. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID] clearDateReadDirectoryID:nil];
  1648. metadata.fileID = metadataNet.fileID;
  1649. metadata.date = metadataNet.date;
  1650. metadata.permissions = @"RDNVCK";
  1651. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1652. [self reloadDatasource];
  1653. } else {
  1654. [self readFileReloadFolder];
  1655. }
  1656. }
  1657. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1658. {
  1659. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1660. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1661. if (![fileNameFolder length]) return;
  1662. //if (autoUploadDirectory) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  1663. //else metadataNet.serverUrl = _serverUrl;
  1664. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1665. if (!directoryID) return;
  1666. metadataNet.action = actionCreateFolder;
  1667. metadataNet.directoryID = directoryID;
  1668. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1669. metadataNet.fileName = fileNameFolder;
  1670. metadataNet.selector = selectorCreateFolder;
  1671. metadataNet.serverUrl = serverUrl;
  1672. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1673. // Create Directory on metadata
  1674. tableMetadata *metadata = [CCUtility createMetadataWithAccount:app.activeAccount date:[NSDate date] directory:YES fileID:metadataNet.fileID directoryID:metadataNet.directoryID fileName:metadataNet.fileName etag:@"" size:0 status:k_metadataStatusNormal];
  1675. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1676. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_serverUrl directoryID:nil];
  1677. [self reloadDatasource];
  1678. }
  1679. #pragma --------------------------------------------------------------------------------------------
  1680. #pragma mark ===== Encrypted / Decrypted Folder =====
  1681. #pragma --------------------------------------------------------------------------------------------
  1682. - (void)encyptedDecryptedFolder
  1683. {
  1684. }
  1685. #pragma --------------------------------------------------------------------------------------------
  1686. #pragma mark ===== Encrypted/Decrypted File =====
  1687. #pragma --------------------------------------------------------------------------------------------
  1688. - (void)encryptedSelectedFiles
  1689. {
  1690. }
  1691. - (void)decryptedSelectedFiles
  1692. {
  1693. }
  1694. - (void)cmdEncryptedDecryptedFile
  1695. {
  1696. }
  1697. - (void)encryptedFile:(tableMetadata *)metadata
  1698. {
  1699. }
  1700. - (void)decryptedFile:(tableMetadata *)metadata
  1701. {
  1702. }
  1703. #pragma --------------------------------------------------------------------------------------------
  1704. #pragma mark ===== Progress & Task Button =====
  1705. #pragma --------------------------------------------------------------------------------------------
  1706. - (void)triggerProgressTask:(NSNotification *)notification
  1707. {
  1708. NSDictionary *dict = notification.userInfo;
  1709. NSString *fileID = [dict valueForKey:@"fileID"];
  1710. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1711. float progress = [[dict valueForKey:@"progress"] floatValue];
  1712. // Check
  1713. if (!fileID || [fileID isEqualToString: @""])
  1714. return;
  1715. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1716. if (![serverUrl isEqualToString:_serverUrl])
  1717. return;
  1718. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1719. if ([self indexPathIsValid:indexPath]) {
  1720. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1721. cell.progressView.progressTintColor = [UIColor blackColor];
  1722. cell.progressView.hidden = NO;
  1723. [cell.progressView setProgress:progress];
  1724. }
  1725. }
  1726. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1727. {
  1728. UITouch * touch = [[event allTouches] anyObject];
  1729. CGPoint location = [touch locationInView:self.tableView];
  1730. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1731. if ([self indexPathIsValid:indexPath]) {
  1732. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1733. if (metadata)
  1734. [self reloadTaskButton:metadata];
  1735. }
  1736. }
  1737. - (void)reloadTaskButton:(tableMetadata *)metadata
  1738. {
  1739. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1740. __block NSURLSessionTask *findTask;
  1741. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1742. NSString *fileID = metadata.fileID;
  1743. // DOWNLOAD
  1744. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1745. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1746. for (NSURLSessionUploadTask *task in downloadTasks)
  1747. if (task.taskIdentifier == sessionTaskIdentifier) {
  1748. findTask = task;
  1749. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1750. [task cancel];
  1751. }
  1752. if (!findTask) {
  1753. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1754. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1755. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1756. }
  1757. }];
  1758. }
  1759. // UPLOAD
  1760. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1761. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1762. for (NSURLSessionUploadTask *task in uploadTasks)
  1763. if (task.taskIdentifier == sessionTaskIdentifier) {
  1764. findTask = task;
  1765. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1766. [task cancel];
  1767. }
  1768. if (!findTask) {
  1769. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1770. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1771. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1772. }
  1773. }];
  1774. }
  1775. }
  1776. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1777. {
  1778. UITouch * touch = [[event allTouches] anyObject];
  1779. CGPoint location = [touch locationInView:self.tableView];
  1780. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1781. if ([self indexPathIsValid:indexPath]) {
  1782. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1783. if (metadata)
  1784. [self cancelTaskButton:metadata reloadTable:YES];
  1785. }
  1786. }
  1787. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  1788. {
  1789. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1790. __block NSURLSessionTask *findTask;
  1791. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1792. NSString *fileID = metadata.fileID;
  1793. // DOWNLOAD
  1794. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1795. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1796. for (NSURLSessionTask *task in downloadTasks)
  1797. if (task.taskIdentifier == sessionTaskIdentifier) {
  1798. findTask = task;
  1799. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1800. [task cancel];
  1801. }
  1802. if (!findTask) {
  1803. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1804. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1805. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1806. }
  1807. }];
  1808. }
  1809. // UPLOAD
  1810. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1811. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1812. for (NSURLSessionUploadTask *task in uploadTasks)
  1813. if (task.taskIdentifier == sessionTaskIdentifier) {
  1814. findTask = task;
  1815. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1816. [task cancel];
  1817. }
  1818. if (!findTask) {
  1819. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1820. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1821. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1822. }
  1823. }];
  1824. }
  1825. }
  1826. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  1827. {
  1828. UITouch * touch = [[event allTouches] anyObject];
  1829. CGPoint location = [touch locationInView:self.tableView];
  1830. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1831. if ([self indexPathIsValid:indexPath]) {
  1832. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1833. if (metadata)
  1834. [self stopTaskButton:metadata];
  1835. }
  1836. }
  1837. - (void)stopTaskButton:(tableMetadata *)metadata
  1838. {
  1839. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1840. __block NSURLSessionTask *findTask;
  1841. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1842. NSString *fileID = metadata.fileID;
  1843. // UPLOAD
  1844. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1845. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1846. for (NSURLSessionUploadTask *task in uploadTasks)
  1847. if (task.taskIdentifier == sessionTaskIdentifier) {
  1848. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1849. findTask = task;
  1850. [task cancel];
  1851. }
  1852. if (!findTask) {
  1853. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1854. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1855. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1856. }
  1857. }];
  1858. }
  1859. }
  1860. #pragma --------------------------------------------------------------------------------------------
  1861. #pragma mark ===== Shared =====
  1862. #pragma --------------------------------------------------------------------------------------------
  1863. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1864. {
  1865. [_hud hideHud];
  1866. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1867. // change account ?
  1868. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1869. if([record.account isEqualToString:metadataNet.account] == NO)
  1870. return;
  1871. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  1872. if (result) {
  1873. appDelegate.sharesLink = result[0];
  1874. appDelegate.sharesUserAndGroup = result[1];
  1875. }
  1876. // Notify Shares View
  1877. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1878. if (openWindow) {
  1879. if (_shareOC) {
  1880. [_shareOC reloadData];
  1881. } else {
  1882. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  1883. // Apriamo la view
  1884. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1885. _shareOC.delegate = self;
  1886. _shareOC.metadata = metadata;
  1887. _shareOC.serverUrl = metadataNet.serverUrl;
  1888. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  1889. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  1890. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1891. [self presentViewController:_shareOC animated:YES completion:nil];
  1892. }
  1893. }
  1894. [self tableViewReloadData];
  1895. }
  1896. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1897. {
  1898. [_hud hideHud];
  1899. // Unauthorized
  1900. if (errorCode == kOCErrorServerUnauthorized)
  1901. [app openLoginView:self loginType:loginModifyPasswordUser];
  1902. if (errorCode != kOCErrorServerUnauthorized)
  1903. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1904. if (_shareOC)
  1905. [_shareOC reloadData];
  1906. [self tableViewReloadData];
  1907. }
  1908. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  1909. {
  1910. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1911. metadataNet.action = actionShare;
  1912. metadataNet.fileID = metadata.fileID;
  1913. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  1914. metadataNet.password = password;
  1915. metadataNet.selector = selectorShare;
  1916. metadataNet.serverUrl = serverUrl;
  1917. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1918. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1919. }
  1920. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  1921. {
  1922. [_hud hideHud];
  1923. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1924. // rimuoviamo la condivisione da db
  1925. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  1926. if (result) {
  1927. appDelegate.sharesLink = result[0];
  1928. appDelegate.sharesUserAndGroup = result[1];
  1929. }
  1930. if (_shareOC)
  1931. [_shareOC reloadData];
  1932. [self tableViewReloadData];
  1933. }
  1934. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1935. {
  1936. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1937. metadataNet.action = actionUnShare;
  1938. metadataNet.fileID = metadata.fileID;
  1939. metadataNet.fileName = metadata.fileName;
  1940. metadataNet.selector = selectorUnshare;
  1941. metadataNet.serverUrl = serverUrl;
  1942. metadataNet.share = share;
  1943. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1944. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1945. }
  1946. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  1947. {
  1948. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1949. metadataNet.action = actionUpdateShare;
  1950. metadataNet.fileID = metadata.fileID;
  1951. metadataNet.expirationTime = expirationTime;
  1952. metadataNet.password = password;
  1953. metadataNet.selector = selectorUpdateShare;
  1954. metadataNet.serverUrl = serverUrl;
  1955. metadataNet.share = share;
  1956. metadataNet.sharePermission = permission;
  1957. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1958. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1959. }
  1960. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  1961. {
  1962. [_hud hideHud];
  1963. if (_shareOC)
  1964. [_shareOC reloadUserAndGroup:items];
  1965. }
  1966. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1967. {
  1968. [_hud hideHud];
  1969. // Unauthorized
  1970. if (errorCode == kOCErrorServerUnauthorized)
  1971. [app openLoginView:self loginType:loginModifyPasswordUser];
  1972. if (errorCode != kOCErrorServerUnauthorized)
  1973. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1974. }
  1975. - (void)getUserAndGroup:(NSString *)find
  1976. {
  1977. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1978. metadataNet.action = actionGetUserAndGroup;
  1979. metadataNet.options = find;
  1980. metadataNet.selector = selectorGetUserAndGroup;
  1981. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1982. [_hud visibleIndeterminateHud];
  1983. }
  1984. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1985. {
  1986. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1987. metadataNet.action = actionShareWith;
  1988. metadataNet.fileID = metadata.fileID;
  1989. metadataNet.directoryID = directoryID;
  1990. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  1991. metadataNet.serverUrl = serverUrl;
  1992. metadataNet.selector = selectorShare;
  1993. metadataNet.share = user;
  1994. metadataNet.shareeType = shareeType;
  1995. metadataNet.sharePermission = permission;
  1996. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1997. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1998. }
  1999. - (void)openWindowShare:(tableMetadata *)metadata
  2000. {
  2001. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2002. if (!serverUrl) return;
  2003. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2004. metadataNet.action = actionReadShareServer;
  2005. metadataNet.fileID = metadata.fileID;
  2006. metadataNet.fileName = metadata.fileName;
  2007. metadataNet.selector = selectorOpenWindowShare;
  2008. metadataNet.serverUrl = serverUrl;
  2009. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2010. [_hud visibleIndeterminateHud];
  2011. }
  2012. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2013. {
  2014. CGPoint location = [tapGesture locationInView:self.tableView];
  2015. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2016. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2017. if (metadata)
  2018. [self openWindowShare:metadata];
  2019. }
  2020. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2021. {
  2022. CGPoint location = [tapGesture locationInView:self.tableView];
  2023. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2024. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2025. if (metadata) {
  2026. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2027. vc.metadata = metadata;
  2028. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2029. [self presentViewController:vc animated:YES completion:nil];
  2030. }
  2031. }
  2032. #pragma --------------------------------------------------------------------------------------------
  2033. #pragma mark ===== Favorite =====
  2034. #pragma --------------------------------------------------------------------------------------------
  2035. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2036. {
  2037. _dateReadDataSource = nil;
  2038. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2039. if (_isSearchMode)
  2040. [self readFolder:metadataNet.serverUrl];
  2041. else
  2042. [self reloadDatasource:metadataNet.serverUrl];
  2043. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2044. if (metadata.directory && metadata.favorite) {
  2045. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileName];
  2046. [app.activeFavorites addFavoriteFolder:dir];
  2047. }
  2048. }
  2049. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2050. {
  2051. // Unauthorized
  2052. if (errorCode == kOCErrorServerUnauthorized)
  2053. [app openLoginView:self loginType:loginModifyPasswordUser];
  2054. NSLog(@"[LOG] Setting Favorite failure error %lu, %@", (long)errorCode, message);
  2055. }
  2056. - (void)addFavorite:(tableMetadata *)metadata
  2057. {
  2058. if (metadata.directory) {
  2059. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2060. } else {
  2061. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2062. if (serverUrl)
  2063. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2064. }
  2065. }
  2066. - (void)removeFavorite:(tableMetadata *)metadata
  2067. {
  2068. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2069. }
  2070. #pragma --------------------------------------------------------------------------------------------
  2071. #pragma mark ===== Open in... =====
  2072. #pragma --------------------------------------------------------------------------------------------
  2073. - (void)openIn:(tableMetadata *)metadata
  2074. {
  2075. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2076. if (!serverUrl) return;
  2077. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2078. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2079. if ([self indexPathIsValid:indexPath])
  2080. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2081. }
  2082. #pragma --------------------------------------------------------------------------------------------
  2083. #pragma mark ===== Remove Local File =====
  2084. #pragma --------------------------------------------------------------------------------------------
  2085. - (void)removeLocalFile:(tableMetadata *)metadata
  2086. {
  2087. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2088. if (!serverUrl) return;
  2089. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2090. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2091. [self reloadDatasource:serverUrl];
  2092. }
  2093. #pragma --------------------------------------------------------------------------------------------
  2094. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2095. #pragma --------------------------------------------------------------------------------------------
  2096. - (void)orderTable:(NSString *)order
  2097. {
  2098. [CCUtility setOrderSettings:order];
  2099. // Clear data-read of DataSource
  2100. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2101. }
  2102. - (void)ascendingTable:(BOOL)ascending
  2103. {
  2104. [CCUtility setAscendingSettings:ascending];
  2105. // Clear data-read of DataSource
  2106. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2107. }
  2108. - (void)directoryOnTop:(BOOL)directoryOnTop
  2109. {
  2110. [CCUtility setDirectoryOnTop:directoryOnTop];
  2111. // Clear data-read of DataSource
  2112. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2113. }
  2114. - (void)tableGroupBy:(NSString *)groupBy
  2115. {
  2116. [CCUtility setGroupBySettings:groupBy];
  2117. // Clear data-read of DataSource
  2118. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2119. }
  2120. #pragma --------------------------------------------------------------------------------------------
  2121. #pragma mark ==== Menu LOGO ====
  2122. #pragma --------------------------------------------------------------------------------------------
  2123. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  2124. {
  2125. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2126. return;
  2127. // Brand
  2128. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2129. return;
  2130. NSUInteger numInSession = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", app.activeAccount] sorted:nil ascending:NO] count];
  2131. NSUInteger numInQueue = [app.netQueue operationCount];
  2132. if (numInSession+numInQueue > 0) {
  2133. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2134. return;
  2135. }
  2136. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2137. NSMutableArray *menuArray = [NSMutableArray new];
  2138. for (NSString *account in listAccount) {
  2139. if ([account isEqualToString:app.activeAccount]) continue;
  2140. CCMenuItem *item = [[CCMenuItem alloc] init];
  2141. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2142. item.argument = account;
  2143. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2144. item.target = self;
  2145. item.action = @selector(changeDefaultAccount:);
  2146. [menuArray addObject:item];
  2147. }
  2148. if ([menuArray count] == 0)
  2149. return;
  2150. OptionalConfiguration options;
  2151. Color textColor, backgroundColor;
  2152. textColor.R = 0;
  2153. textColor.G = 0;
  2154. textColor.B = 0;
  2155. backgroundColor.R = 1;
  2156. backgroundColor.G = 1;
  2157. backgroundColor.B = 1;
  2158. options.arrowSize = 9;
  2159. options.marginXSpacing = 7;
  2160. options.marginYSpacing = 10;
  2161. options.intervalSpacing = 20;
  2162. options.menuCornerRadius = 6.5;
  2163. options.maskToBackground = NO;
  2164. options.shadowOfMenu = YES;
  2165. options.hasSeperatorLine = YES;
  2166. options.seperatorLineHasInsets = YES;
  2167. options.textColor = textColor;
  2168. options.menuBackgroundColor = backgroundColor;
  2169. CGRect rect = self.view.frame;
  2170. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  2171. CGFloat safeAreaTop = 0;
  2172. CGFloat offsetY = 35;
  2173. if (@available(iOS 11, *)) {
  2174. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  2175. }
  2176. rect.origin.y = locationY + safeAreaTop + offsetY;
  2177. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  2178. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2179. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2180. }
  2181. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2182. {
  2183. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2184. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2185. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2186. if (tableAccount)
  2187. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  2188. // go to home sweet home
  2189. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2190. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2191. });
  2192. }
  2193. #pragma --------------------------------------------------------------------------------------------
  2194. #pragma mark ==== ReMenu ====
  2195. #pragma --------------------------------------------------------------------------------------------
  2196. - (void)createReMenuBackgroundView:(REMenu *)menu
  2197. {
  2198. CGFloat safeAreaBottom = 0;
  2199. CGFloat safeAreaTop = 0;
  2200. CGFloat statusBar = 0;
  2201. if (@available(iOS 11, *)) {
  2202. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  2203. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  2204. }
  2205. if ([UIApplication sharedApplication].isStatusBarHidden) {
  2206. statusBar = 13;
  2207. }
  2208. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  2209. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  2210. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  2211. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  2212. [UIView animateWithDuration:0.2 animations:^{
  2213. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  2214. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  2215. if (y>minimum) {
  2216. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  2217. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2218. }
  2219. }];
  2220. }
  2221. - (void)createReMainMenu
  2222. {
  2223. NSString *ordinamento;
  2224. NSString *groupBy = _directoryGroupBy;
  2225. __block NSString *nuovoOrdinamento;
  2226. NSString *titoloNuovo, *titoloAttuale;
  2227. BOOL ascendente;
  2228. __block BOOL nuovoAscendente;
  2229. UIImage *image;
  2230. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2231. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2232. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2233. [self tableViewSelect:YES];
  2234. }
  2235. }];
  2236. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2237. ordinamento = _directoryOrder;
  2238. if ([ordinamento isEqualToString:@"fileName"]) {
  2239. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2240. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2241. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2242. nuovoOrdinamento = @"date";
  2243. }
  2244. if ([ordinamento isEqualToString:@"date"]) {
  2245. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2246. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2247. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2248. nuovoOrdinamento = @"fileName";
  2249. }
  2250. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2251. [self orderTable:nuovoOrdinamento];
  2252. }];
  2253. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2254. ascendente = [CCUtility getAscendingSettings];
  2255. if (ascendente) {
  2256. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2257. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2258. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2259. nuovoAscendente = false;
  2260. }
  2261. if (!ascendente) {
  2262. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2263. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2264. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2265. nuovoAscendente = true;
  2266. }
  2267. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2268. [self ascendingTable:nuovoAscendente];
  2269. }];
  2270. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2271. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2272. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2273. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2274. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2275. else [self tableGroupBy:@"alphabetic"];
  2276. }];
  2277. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2278. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2279. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2280. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2281. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2282. else [self tableGroupBy:@"typefile"];
  2283. }];
  2284. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2285. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2286. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2287. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2288. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2289. else [self tableGroupBy:@"date"];
  2290. }];
  2291. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2292. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2293. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2294. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2295. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2296. else [self directoryOnTop:YES];
  2297. }];
  2298. // REMENU --------------------------------------------------------------------------------------------------------------
  2299. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2300. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2301. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2302. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2303. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2304. app.reMainMenu.separatorHeight = 0.5;
  2305. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2306. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2307. app.reMainMenu.textColor = [UIColor blackColor];
  2308. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2309. app.reMainMenu.textShadowColor = nil;
  2310. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2311. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2312. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2313. app.reMainMenu.highlightedSeparatorColor = nil;
  2314. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2315. app.reMainMenu.highlightedTextShadowColor = nil;
  2316. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2317. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2318. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2319. app.reMainMenu.subtitleTextShadowColor = nil;
  2320. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2321. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2322. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2323. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2324. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2325. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2326. app.reMainMenu.borderWidth = 0.3;
  2327. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2328. app.reMainMenu.animationDuration = 0.2;
  2329. app.reMainMenu.closeAnimationDuration = 0.2;
  2330. app.reMainMenu.bounce = NO;
  2331. [app.reMainMenu setClosePreparationBlock:^{
  2332. // Backgroun reMenu (Gesture)
  2333. [_reMenuBackgroundView removeFromSuperview];
  2334. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2335. }];
  2336. }
  2337. - (void)toggleReMainMenu
  2338. {
  2339. if (app.reMainMenu.isOpen) {
  2340. [app.reMainMenu close];
  2341. } else {
  2342. [self createReMainMenu];
  2343. [app.reMainMenu showFromNavigationController:self.navigationController];
  2344. // Backgroun reMenu & (Gesture)
  2345. [self createReMenuBackgroundView:app.reMainMenu];
  2346. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2347. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2348. }
  2349. }
  2350. - (void)createReSelectMenu
  2351. {
  2352. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2353. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2354. [self deleteFile];
  2355. }];
  2356. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2357. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2358. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2359. }];
  2360. /*
  2361. if (app.isCryptoCloudMode) {
  2362. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2363. app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"encryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2364. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2365. }];
  2366. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2367. app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"decryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2368. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2369. }];
  2370. }
  2371. */
  2372. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2373. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_folders_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2374. [self downloadSelectedFilesFolders];
  2375. }];
  2376. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2377. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2378. [self saveSelectedFiles];
  2379. }];
  2380. // REMENU --------------------------------------------------------------------------------------------------------------
  2381. /*
  2382. if (app.isCryptoCloudMode) {
  2383. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2384. } else {
  2385. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2386. }
  2387. */
  2388. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2389. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2390. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2391. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2392. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2393. app.reSelectMenu.separatorHeight = 0.5;
  2394. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2395. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2396. app.reSelectMenu.textColor = [UIColor blackColor];
  2397. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2398. app.reSelectMenu.textShadowColor = nil;
  2399. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2400. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2401. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2402. app.reSelectMenu.highlightedSeparatorColor = nil;
  2403. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2404. app.reSelectMenu.highlightedTextShadowColor = nil;
  2405. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2406. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2407. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2408. app.reSelectMenu.subtitleTextShadowColor = nil;
  2409. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2410. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2411. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2412. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2413. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2414. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2415. app.reSelectMenu.borderWidth = 0.3;
  2416. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2417. app.reSelectMenu.closeAnimationDuration = 0.2;
  2418. app.reSelectMenu.animationDuration = 0.2;
  2419. app.reSelectMenu.bounce = NO;
  2420. [app.reSelectMenu setClosePreparationBlock:^{
  2421. // Backgroun reMenu (Gesture)
  2422. [_reMenuBackgroundView removeFromSuperview];
  2423. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2424. }];
  2425. }
  2426. - (void)toggleReSelectMenu
  2427. {
  2428. if (app.reSelectMenu.isOpen) {
  2429. [app.reSelectMenu close];
  2430. } else {
  2431. [self createReSelectMenu];
  2432. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2433. // Backgroun reMenu & (Gesture)
  2434. [self createReMenuBackgroundView:app.reSelectMenu];
  2435. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2436. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2437. }
  2438. }
  2439. #pragma --------------------------------------------------------------------------------------------
  2440. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2441. #pragma --------------------------------------------------------------------------------------------
  2442. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2443. {
  2444. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2445. UITableView *tableView = (UITableView*)self.view;
  2446. CGPoint touchPoint = [recognizer locationInView:self.view];
  2447. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2448. if ([self indexPathIsValid:indexPath])
  2449. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2450. else
  2451. _metadata = nil;
  2452. [self becomeFirstResponder];
  2453. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2454. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2455. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2456. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2457. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2458. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2459. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2460. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2461. [menuController setMenuVisible:YES animated:YES];
  2462. }
  2463. }
  2464. - (BOOL)canBecomeFirstResponder
  2465. {
  2466. return YES;
  2467. }
  2468. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2469. {
  2470. // For copy file, copy files, Open in ... :
  2471. //
  2472. // NO Directory
  2473. // NO Error Passcode
  2474. // NO In Session mode (download/upload)
  2475. // NO Template
  2476. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2477. if (_isSelectedMode == NO && _metadata && !_metadata.directory && [_metadata.session length] == 0) return YES;
  2478. else return NO;
  2479. }
  2480. if (@selector(copyFiles:) == action) {
  2481. if (_isSelectedMode) {
  2482. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2483. for (tableMetadata *metadata in selectedMetadatas) {
  2484. if (!metadata.directory && metadata.session.length == 0)
  2485. return YES;
  2486. }
  2487. }
  2488. return NO;
  2489. }
  2490. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2491. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2492. NSArray *items = [pasteboard items];
  2493. if ([items count] == 1) {
  2494. // Value : (NSData) fileID
  2495. NSDictionary *dic = [items objectAtIndex:0];
  2496. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2497. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2498. if (fileID) {
  2499. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2500. if (metadata) {
  2501. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2502. if (account) {
  2503. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2504. if (directoryUser)
  2505. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2506. return YES;
  2507. }
  2508. }
  2509. }
  2510. }
  2511. return NO;
  2512. }
  2513. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2514. BOOL isValid = NO;
  2515. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2516. NSArray *items = [pasteboard items];
  2517. if ([items count] <= 1) return NO;
  2518. for (NSDictionary *dic in items) {
  2519. // Value : (NSData) fileID
  2520. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2521. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2522. if (fileID) {
  2523. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2524. if (metadata) {
  2525. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2526. if (account) {
  2527. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2528. if (directoryUser) {
  2529. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2530. isValid = YES;
  2531. } else {
  2532. isValid = NO;
  2533. break;
  2534. }
  2535. } else {
  2536. isValid = NO;
  2537. break;
  2538. }
  2539. } else {
  2540. isValid = NO;
  2541. break;
  2542. }
  2543. } else {
  2544. isValid = NO;
  2545. break;
  2546. }
  2547. } else {
  2548. isValid = NO;
  2549. break;
  2550. }
  2551. }
  2552. return isValid;
  2553. }
  2554. return NO;
  2555. }
  2556. /************************************ COPY ************************************/
  2557. - (void)copyFile:(id)sender
  2558. {
  2559. // Remove all item
  2560. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2561. pasteboard.items = [[NSArray alloc] init];
  2562. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2563. [self copyFileToPasteboard:_metadata];
  2564. } else {
  2565. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2566. if (serverUrl)
  2567. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2568. }
  2569. }
  2570. - (void)copyFiles:(id)sender
  2571. {
  2572. // Remove all item
  2573. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2574. pasteboard.items = [[NSArray alloc] init];
  2575. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2576. for (tableMetadata *metadata in selectedMetadatas) {
  2577. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2578. [self copyFileToPasteboard:metadata];
  2579. } else {
  2580. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2581. if (serverUrl)
  2582. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2583. }
  2584. }
  2585. [self tableViewSelect:NO];
  2586. }
  2587. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2588. {
  2589. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2590. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2591. // Value : (NSData) fileID
  2592. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2593. [items addObject:item];
  2594. [pasteboard setItems:items];
  2595. }
  2596. /************************************ OPEN IN ... ******************************/
  2597. - (void)openinFile:(id)sender
  2598. {
  2599. [self openIn:_metadata];
  2600. }
  2601. /************************************ PASTE ************************************/
  2602. - (void)pasteFile:(id)sender
  2603. {
  2604. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2605. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2606. }
  2607. - (void)pasteFileEncrypted:(id)sender
  2608. {
  2609. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2610. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2611. }
  2612. - (void)pasteFiles:(id)sender
  2613. {
  2614. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2615. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2616. }
  2617. - (void)pasteFilesEncrypted:(id)sender
  2618. {
  2619. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2620. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2621. }
  2622. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2623. {
  2624. float timer = 0;
  2625. for (NSDictionary *dic in items) {
  2626. // Value : (NSData) fileID
  2627. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2628. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2629. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2630. if (metadata) {
  2631. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2632. if (account) {
  2633. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2634. if (directoryUser) {
  2635. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2636. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName]];
  2637. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2638. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:_serverUrl session:k_upload_session taskStatus:k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  2639. });
  2640. timer += 0.1;
  2641. }
  2642. }
  2643. }
  2644. }
  2645. }
  2646. }
  2647. #pragma --------------------------------------------------------------------------------------------
  2648. #pragma mark ===== Lock Passcode =====
  2649. #pragma --------------------------------------------------------------------------------------------
  2650. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2651. {
  2652. return _failedAttempts;
  2653. }
  2654. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2655. {
  2656. return _lockUntilDate;
  2657. }
  2658. - (void)passcodeViewCloseButtonPressed:(id)sender
  2659. {
  2660. [self dismissViewControllerAnimated:YES completion:nil];
  2661. }
  2662. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2663. {
  2664. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2665. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2666. _lockUntilDate = nil;
  2667. _failedAttempts = 0;
  2668. aResultHandler(YES);
  2669. } else aResultHandler(NO);
  2670. } else aResultHandler(YES);
  2671. }
  2672. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2673. {
  2674. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2675. switch (aViewController.type) {
  2676. case BKPasscodeViewControllerCheckPasscodeType: {
  2677. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2678. // possiamo procedere alla prossima directory
  2679. [self performSegueDirectoryWithControlPasscode:false];
  2680. // avviamo la sessione Passcode Lock con now
  2681. app.sessionePasscodeLock = [NSDate date];
  2682. }
  2683. // disattivazione lock cartella
  2684. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2685. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2686. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2687. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2688. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2689. }
  2690. [self tableViewReloadData];
  2691. }
  2692. }
  2693. break;
  2694. default:
  2695. break;
  2696. }
  2697. }
  2698. - (void)comandoLockPassword
  2699. {
  2700. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2701. if (!serverUrl) return;
  2702. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2703. // se non è abilitato il Lock Passcode esci
  2704. if ([[CCUtility getBlockCode] length] == 0) {
  2705. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2706. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2707. [alertController addAction:okAction];
  2708. [self presentViewController:alertController animated:YES completion:nil];
  2709. return;
  2710. }
  2711. // se è richiesta la disattivazione si chiede la password
  2712. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2713. if (directory.lock) {
  2714. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2715. viewController.delegate = self;
  2716. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2717. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2718. viewController.inputViewTitlePassword = YES;
  2719. if ([CCUtility getSimplyBlockCode]) {
  2720. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2721. viewController.passcodeInputView.maximumLength = 6;
  2722. } else {
  2723. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2724. viewController.passcodeInputView.maximumLength = 64;
  2725. }
  2726. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2727. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2728. viewController.touchIDManager = touchIDManager;
  2729. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2730. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2731. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2732. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2733. [self presentViewController:navigationController animated:YES completion:nil];
  2734. return;
  2735. }
  2736. // ---------------- ACTIVATE PASSWORD
  2737. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2738. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2739. if ([self indexPathIsValid:indexPath])
  2740. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2741. } else {
  2742. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2743. }
  2744. }
  2745. #pragma mark -
  2746. #pragma --------------------------------------------------------------------------------------------
  2747. #pragma mark ===== Swipe Tablet -> menu =====
  2748. #pragma --------------------------------------------------------------------------------------------
  2749. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2750. {
  2751. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2752. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2753. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2754. return NO;
  2755. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  2756. return NO;
  2757. else
  2758. return YES;
  2759. }
  2760. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2761. {
  2762. }
  2763. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2764. {
  2765. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2766. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2767. if (direction == MGSwipeDirectionRightToLeft) {
  2768. // Delete
  2769. if (index == 0)
  2770. [self swipeDelete:indexPath];
  2771. // More
  2772. if (index == 1)
  2773. [self swipeMore:indexPath];
  2774. }
  2775. if (direction == MGSwipeDirectionLeftToRight) {
  2776. if (_metadata.favorite)
  2777. [self removeFavorite:_metadata];
  2778. else
  2779. [self addFavorite:_metadata];
  2780. }
  2781. return YES;
  2782. }
  2783. - (void)swipeDelete:(NSIndexPath *)indexPath
  2784. {
  2785. // Directory locked ?
  2786. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileName];
  2787. if (!lockServerUrl) return;
  2788. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2789. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) {
  2790. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2791. return;
  2792. }
  2793. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2794. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2795. [self performSelector:@selector(deleteFile) withObject:nil];
  2796. }]];
  2797. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2798. [alertController dismissViewControllerAnimated:YES completion:nil];
  2799. }]];
  2800. alertController.popoverPresentationController.sourceView = self.view;
  2801. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2802. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2803. [alertController.view layoutIfNeeded];
  2804. [self presentViewController:alertController animated:YES completion:nil];
  2805. }
  2806. - (void)swipeMore:(NSIndexPath *)indexPath
  2807. {
  2808. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2809. if (!serverUrl) return;
  2810. NSString *titoloCriptaDecripta, *titoloLock, *titleFavorite;
  2811. titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  2812. if (_metadata.favorite) {
  2813. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2814. } else {
  2815. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2816. }
  2817. if (_metadata.directory) {
  2818. // calcolo lockServerUrl
  2819. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2820. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2821. if (directory.lock)
  2822. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2823. else
  2824. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2825. }
  2826. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  2827. // ******************************************* AHKActionSheet *******************************************
  2828. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2829. actionSheet.animationDuration = 0.2;
  2830. actionSheet.buttonHeight = 50.0;
  2831. actionSheet.cancelButtonHeight = 50.0f;
  2832. actionSheet.separatorHeight = 5.0f;
  2833. actionSheet.automaticallyTintButtonImages = @(NO);
  2834. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  2835. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2836. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2837. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor darkGrayColor] };
  2838. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2839. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2840. // ******************************************* DIRECTORY *******************************************
  2841. if (_metadata.directory) {
  2842. BOOL lockDirectory = NO;
  2843. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2844. // Directory bloccata ?
  2845. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, dirServerUrl]];
  2846. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  2847. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  2848. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  2849. [actionSheet addButtonWithTitle: _metadata.fileName
  2850. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  2851. backgroundColor: [NCBrandColor sharedInstance].tabBar
  2852. height: 50.0
  2853. type: AHKActionSheetButtonTypeDisabled
  2854. handler: nil
  2855. ];
  2856. if (!lockDirectory) {
  2857. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2858. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  2859. backgroundColor:[UIColor whiteColor]
  2860. height: 50.0
  2861. type:AHKActionSheetButtonTypeDefault
  2862. handler:^(AHKActionSheet *as) {
  2863. [self openWindowShare:_metadata];
  2864. }];
  2865. }
  2866. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  2867. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2868. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  2869. backgroundColor:[UIColor whiteColor]
  2870. height: 50.0
  2871. type:AHKActionSheetButtonTypeDefault
  2872. handler:^(AHKActionSheet *as) {
  2873. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2874. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2875. textField.text = _metadata.fileName;
  2876. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  2877. //textField.delegate = self;
  2878. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2879. }];
  2880. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2881. NSLog(@"Cancel action");
  2882. }];
  2883. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2884. UITextField *fileName = alertController.textFields.firstObject;
  2885. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  2886. }];
  2887. okAction.enabled = NO;
  2888. [alertController addAction:cancelAction];
  2889. [alertController addAction:okAction];
  2890. [self presentViewController:alertController animated:YES completion:nil];
  2891. }];
  2892. }
  2893. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  2894. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2895. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  2896. backgroundColor:[UIColor whiteColor]
  2897. height: 50.0
  2898. type:AHKActionSheetButtonTypeDefault
  2899. handler:^(AHKActionSheet *as) {
  2900. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2901. }];
  2902. }
  2903. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  2904. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  2905. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  2906. backgroundColor:[UIColor whiteColor]
  2907. height: 50.0
  2908. type:AHKActionSheetButtonTypeDefault
  2909. handler:^(AHKActionSheet *as) {
  2910. // Settings new folder Automatatic upload
  2911. NSString *oldAutoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  2912. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  2913. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:app.activeUrl];
  2914. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:oldAutoUploadDirectory directoryID:nil];
  2915. if (app.activeAccount.length > 0 && app.activePhotos)
  2916. [app.activePhotos reloadDatasourceForced];
  2917. [self readFolder:serverUrl];
  2918. NSLog(@"[LOG] Update Folder Photo");
  2919. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  2920. if ([autoUploadPath length] > 0) {
  2921. [[CCSynchronize sharedSynchronize] readFileForFolder:_metadata.fileName serverUrl:serverUrl selector:selectorReadFileFolder];
  2922. }
  2923. }];
  2924. }
  2925. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  2926. [actionSheet addButtonWithTitle:titoloLock
  2927. image:[UIImage imageNamed:@"actionSheetLock"]
  2928. backgroundColor:[UIColor whiteColor]
  2929. height: 50.0
  2930. type:AHKActionSheetButtonTypeEncrypted
  2931. handler:^(AHKActionSheet *as) {
  2932. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2933. }];
  2934. }
  2935. /*
  2936. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  2937. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  2938. image:[UIImage imageNamed:@"actionSheetCrypto"]
  2939. backgroundColor:[UIColor whiteColor]
  2940. height: 50.0
  2941. type:AHKActionSheetButtonTypeEncrypted
  2942. handler:^(AHKActionSheet *as) {
  2943. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  2944. }];
  2945. }
  2946. */
  2947. [actionSheet show];
  2948. }
  2949. // ******************************************* FILE *******************************************
  2950. if (!_metadata.directory) {
  2951. UIImage *iconHeader;
  2952. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  2953. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  2954. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  2955. else
  2956. iconHeader = [UIImage imageNamed:_metadata.iconName];
  2957. [actionSheet addButtonWithTitle: _metadata.fileName
  2958. image: iconHeader
  2959. backgroundColor: [NCBrandColor sharedInstance].tabBar
  2960. height: 50.0
  2961. type: AHKActionSheetButtonTypeDisabled
  2962. handler: nil
  2963. ];
  2964. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2965. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"]color:[NCBrandColor sharedInstance].brand]
  2966. backgroundColor:[UIColor whiteColor]
  2967. height: 50.0
  2968. type:AHKActionSheetButtonTypeDefault
  2969. handler:^(AHKActionSheet *as) {
  2970. [self openWindowShare:_metadata];
  2971. }];
  2972. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  2973. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  2974. backgroundColor:[UIColor whiteColor]
  2975. height: 50.0
  2976. type:AHKActionSheetButtonTypeDefault
  2977. handler:^(AHKActionSheet *as) {
  2978. [self performSelector:@selector(openIn:) withObject:_metadata];
  2979. }];
  2980. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2981. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  2982. backgroundColor:[UIColor whiteColor]
  2983. height: 50.0
  2984. type:AHKActionSheetButtonTypeDefault
  2985. handler:^(AHKActionSheet *as) {
  2986. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2987. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2988. textField.text = _metadata.fileName;
  2989. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2990. }];
  2991. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2992. NSLog(@"Cancel action");
  2993. }];
  2994. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2995. UITextField *fileName = alertController.textFields.firstObject;
  2996. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  2997. }];
  2998. okAction.enabled = NO;
  2999. [alertController addAction:cancelAction];
  3000. [alertController addAction:okAction];
  3001. [self presentViewController:alertController animated:YES completion:nil];
  3002. }];
  3003. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3004. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3005. backgroundColor:[UIColor whiteColor]
  3006. height: 50.0
  3007. type:AHKActionSheetButtonTypeDefault
  3008. handler:^(AHKActionSheet *as) {
  3009. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3010. }];
  3011. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3012. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3013. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3014. backgroundColor:[UIColor whiteColor]
  3015. height: 50.0
  3016. type:AHKActionSheetButtonTypeDefault
  3017. handler:^(AHKActionSheet *as) {
  3018. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3019. }];
  3020. }
  3021. /*
  3022. if (app.isCryptoCloudMode) {
  3023. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3024. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3025. backgroundColor:[UIColor whiteColor]
  3026. height: 50.0
  3027. type:AHKActionSheetButtonTypeEncrypted
  3028. handler:^(AHKActionSheet *as) {
  3029. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3030. }];
  3031. }
  3032. */
  3033. #ifdef DEBUG
  3034. /*
  3035. [actionSheet addButtonWithTitle:@"Hide file"
  3036. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"admin"] color:[NCBrandColor sharedInstance].brand]
  3037. backgroundColor:[UIColor whiteColor]
  3038. height: 50.0
  3039. type:AHKActionSheetButtonTypeDefault
  3040. handler:^(AHKActionSheet *as) {
  3041. [[NCManageDatabase sharedInstance] setMetadataStatusWithFileID:_metadata.fileID status:k_metadataStatusHide];
  3042. [self reloadDatasource];
  3043. }];
  3044. */
  3045. #endif
  3046. [actionSheet show];
  3047. }
  3048. }
  3049. #pragma --------------------------------------------------------------------------------------------
  3050. #pragma mark - ==== Datasource ====
  3051. #pragma --------------------------------------------------------------------------------------------
  3052. - (void)clearDateReadDataSource:(NSNotification *)notification
  3053. {
  3054. _dateReadDataSource = Nil;
  3055. [self reloadDatasource];
  3056. }
  3057. - (void)reloadDatasource
  3058. {
  3059. [self reloadDatasource:_serverUrl];
  3060. }
  3061. - (void)reloadDatasource:(NSString *)serverUrl
  3062. {
  3063. // test
  3064. if (app.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil)
  3065. return;
  3066. // Search Mode
  3067. if(_isSearchMode) {
  3068. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:app.activeAccount];
  3069. [self tableViewReloadData];
  3070. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3071. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3072. _noFilesSearchDescription = @"";
  3073. }
  3074. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3075. _noFilesSearchTitle = @"";
  3076. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3077. }
  3078. [self.tableView reloadEmptyDataSet];
  3079. return;
  3080. }
  3081. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3082. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3083. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3084. if (main) {
  3085. [main reloadDatasource];
  3086. } else {
  3087. [self tableViewReloadData];
  3088. [app.activeTransfers reloadDatasource];
  3089. }
  3090. return;
  3091. }
  3092. [app.activeTransfers reloadDatasource];
  3093. // Settaggio variabili per le ottimizzazioni
  3094. _directoryGroupBy = [CCUtility getGroupBySettings];
  3095. _directoryOrder = [CCUtility getOrderSettings];
  3096. // Controllo data lettura Data Source
  3097. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  3098. NSDate *dateDateRecordDirectory = directory.dateReadDirectory;
  3099. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3100. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3101. _dateReadDataSource = [NSDate date];
  3102. // Data Source
  3103. NSString *sorted = _directoryOrder;
  3104. if ([sorted isEqualToString:@"fileName"])
  3105. sorted = @"fileName";
  3106. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  3107. if (directoryID) {
  3108. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND status = %i", app.activeAccount, directoryID, k_metadataStatusNormal] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  3109. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3110. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:app.activeAccount];
  3111. }
  3112. } else {
  3113. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3114. }
  3115. [self tableViewReloadData];
  3116. }
  3117. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3118. {
  3119. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3120. if (selectedRows.count > 0) {
  3121. for (NSIndexPath *selectionIndex in selectedRows) {
  3122. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3123. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3124. [metadatas addObject:metadata];
  3125. }
  3126. }
  3127. return metadatas;
  3128. }
  3129. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3130. {
  3131. NSInteger section = indexPath.section + 1;
  3132. NSInteger row = indexPath.row + 1;
  3133. NSInteger totSections = [_sectionDataSource.sections count] ;
  3134. if ((totSections < section) || (section > totSections)) {
  3135. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3136. return nil;
  3137. }
  3138. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3139. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3140. if (fileIDs) {
  3141. NSInteger totRows =[fileIDs count] ;
  3142. if ((totRows < row) || (row > totRows)) {
  3143. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3144. return nil;
  3145. }
  3146. } else {
  3147. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3148. return nil;
  3149. }
  3150. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3151. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3152. return metadata;
  3153. }
  3154. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3155. {
  3156. NSInteger totSections =[_sectionDataSource.sections count] ;
  3157. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3158. return nil;
  3159. }
  3160. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3161. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3162. }
  3163. #pragma --------------------------------------------------------------------------------------------
  3164. #pragma mark - ==== Table ====
  3165. #pragma --------------------------------------------------------------------------------------------
  3166. - (void)tableViewSelect:(BOOL)edit
  3167. {
  3168. // chiudiamo eventuali swipe aperti
  3169. if (edit)
  3170. [self.tableView setEditing:NO animated:NO];
  3171. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3172. [self.tableView setEditing:edit animated:YES];
  3173. _isSelectedMode = edit;
  3174. if (edit)
  3175. [self setUINavigationBarSelected];
  3176. else
  3177. [self setUINavigationBarDefault];
  3178. [_selectedFileIDsMetadatas removeAllObjects];
  3179. [self setTitle];
  3180. }
  3181. - (void)tableViewReloadData
  3182. {
  3183. // store selected cells before relod
  3184. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3185. //store swipeOffset before relod
  3186. [_statusSwipeCell removeAllObjects];
  3187. for (MGSwipeTableCell *cell in self.tableView.visibleCells) {
  3188. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  3189. [_statusSwipeCell setObject:[NSNumber numberWithDouble:cell.swipeOffset] forKey:indexPath];
  3190. }
  3191. // reload table view
  3192. [self.tableView reloadData];
  3193. // selected cells stored
  3194. for (NSIndexPath *path in indexPaths)
  3195. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3196. [self setTableViewFooter];
  3197. if (self.tableView.editing)
  3198. [self setTitle];
  3199. }
  3200. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3201. {
  3202. if (tableView.editing == 1) {
  3203. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3204. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3205. return NO;
  3206. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  3207. return NO;
  3208. else
  3209. return YES;
  3210. } else {
  3211. [_selectedFileIDsMetadatas removeAllObjects];
  3212. }
  3213. return YES;
  3214. }
  3215. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3216. {
  3217. return 60;
  3218. }
  3219. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3220. {
  3221. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3222. }
  3223. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3224. {
  3225. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3226. }
  3227. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3228. {
  3229. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3230. NSString *sectionTitle = [sections objectAtIndex:section];
  3231. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3232. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3233. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3234. return 20.f;
  3235. }
  3236. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3237. {
  3238. float shift;
  3239. UIVisualEffectView *visualEffectView;
  3240. NSString *titleSection;
  3241. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3242. return nil;
  3243. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3244. titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3245. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3246. titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3247. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3248. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3249. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3250. else titleSection = NSLocalizedString(titleSection,nil);
  3251. // Format title
  3252. NSString *currentDevice = [CCUtility currentDevice];
  3253. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3254. visualEffectView = [[UIVisualEffectView alloc] init];
  3255. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3256. } else {
  3257. UIVisualEffect *blurEffect;
  3258. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3259. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3260. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3261. }
  3262. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3263. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3264. shift = - 35;
  3265. else
  3266. shift = - 20;
  3267. } else shift = - 10;
  3268. // Title
  3269. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3270. titleLabel.backgroundColor = [UIColor clearColor];
  3271. titleLabel.textColor = [UIColor blackColor];
  3272. titleLabel.font = [UIFont systemFontOfSize:12];
  3273. titleLabel.textAlignment = NSTextAlignmentLeft;
  3274. titleLabel.text = titleSection;
  3275. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3276. [visualEffectView.contentView addSubview:titleLabel];
  3277. // Elements
  3278. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3279. elementLabel.backgroundColor = [UIColor clearColor];
  3280. elementLabel.textColor = [UIColor blackColor];;
  3281. elementLabel.font = [UIFont systemFontOfSize:12];
  3282. elementLabel.textAlignment = NSTextAlignmentRight;
  3283. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3284. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3285. NSUInteger rowsCount = [metadatas count];
  3286. if (rowsCount == 0) return nil;
  3287. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3288. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3289. [visualEffectView.contentView addSubview:elementLabel];
  3290. return visualEffectView;
  3291. }
  3292. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3293. {
  3294. return [_sectionDataSource.sections indexOfObject:title];
  3295. }
  3296. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3297. {
  3298. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3299. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3300. else
  3301. return nil;
  3302. }
  3303. /*
  3304. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3305. {
  3306. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3307. }
  3308. }
  3309. */
  3310. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3311. {
  3312. NSString *typeCell;
  3313. NSString *dataFile;
  3314. NSString *lunghezzaFile;
  3315. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3316. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3317. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3318. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3319. if (!serverUrl)
  3320. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3321. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3322. else typeCell = @"CellMainTransfer";
  3323. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3324. // variable base
  3325. cell.delegate = self;
  3326. cell.indexPath = indexPath;
  3327. // separator
  3328. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3329. // change color selection
  3330. UIView *selectionColor = [[UIView alloc] init];
  3331. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3332. cell.selectedBackgroundView = selectionColor;
  3333. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3334. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3335. // ----------------------------------------------------------------------------------------------------------
  3336. // DEFAULT
  3337. // ----------------------------------------------------------------------------------------------------------
  3338. cell.file.image = nil;
  3339. cell.status.image = nil;
  3340. cell.favorite.image = nil;
  3341. cell.shared.image = nil;
  3342. cell.local.image = nil;
  3343. cell.labelTitle.enabled = YES;
  3344. cell.labelTitle.text = @"";
  3345. cell.labelInfoFile.enabled = YES;
  3346. cell.labelInfoFile.text = @"";
  3347. cell.progressView.progress = 0.0;
  3348. cell.progressView.hidden = YES;
  3349. cell.cancelTaskButton.hidden = YES;
  3350. cell.reloadTaskButton.hidden = YES;
  3351. cell.stopTaskButton.hidden = YES;
  3352. cell.labelTitle.textColor = [UIColor blackColor];
  3353. // ----------------------------------------------------------------------------------------------------------
  3354. // File Name & Folder
  3355. // ----------------------------------------------------------------------------------------------------------
  3356. // nome del file
  3357. cell.labelTitle.text = metadata.fileName;
  3358. // è una directory
  3359. if (metadata.directory) {
  3360. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3361. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3362. lunghezzaFile = @" ";
  3363. // ----------------------------------------------------------------------------------------------------------
  3364. // Favorite Folder
  3365. // ----------------------------------------------------------------------------------------------------------
  3366. if (metadata.favorite) {
  3367. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3368. }
  3369. } else {
  3370. // File
  3371. dataFile = [CCUtility dateDiff:metadata.date];
  3372. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3373. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3374. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3375. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3376. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3377. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3378. cell.local.image = [UIImage imageNamed:@"local"];
  3379. else
  3380. cell.local.image = nil;
  3381. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3382. cell.accessoryType = UITableViewCellAccessoryNone;
  3383. }
  3384. // ----------------------------------------------------------------------------------------------------------
  3385. // File Image View
  3386. // ----------------------------------------------------------------------------------------------------------
  3387. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3388. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3389. cell.file.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3390. } else {
  3391. if (metadata.directory)
  3392. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3393. else
  3394. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3395. if (metadata.thumbnailExists)
  3396. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3397. }
  3398. // ----------------------------------------------------------------------------------------------------------
  3399. // Image Status cyptated & Lock Passcode
  3400. // ----------------------------------------------------------------------------------------------------------
  3401. // Directory con passcode lock attivato
  3402. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  3403. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3404. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3405. cell.status.image = [UIImage imageNamed:@"passcode"];
  3406. // ----------------------------------------------------------------------------------------------------------
  3407. // Favorite
  3408. // ----------------------------------------------------------------------------------------------------------
  3409. if (metadata.favorite) {
  3410. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3411. }
  3412. // ----------------------------------------------------------------------------------------------------------
  3413. // Share
  3414. // ----------------------------------------------------------------------------------------------------------
  3415. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3416. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3417. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3418. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3419. // Aggiungiamo il Tap per le shared
  3420. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3421. // Shared with you
  3422. if (isShare) {
  3423. if (metadata.directory) {
  3424. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3425. cell.accessoryType = UITableViewCellAccessoryNone;
  3426. }
  3427. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3428. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3429. [tap setNumberOfTapsRequired:1];
  3430. cell.shared.userInteractionEnabled = YES;
  3431. [cell.shared addGestureRecognizer:tap];
  3432. }
  3433. // Mounted with you
  3434. if (isMounted) {
  3435. if (metadata.directory) {
  3436. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3437. cell.accessoryType = UITableViewCellAccessoryNone;
  3438. }
  3439. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3440. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3441. [tap setNumberOfTapsRequired:1];
  3442. cell.shared.userInteractionEnabled = YES;
  3443. [cell.shared addGestureRecognizer:tap];
  3444. }
  3445. // You share
  3446. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3447. if (metadata.directory) {
  3448. if ([shareLink length] > 0)
  3449. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3450. if ([shareUserAndGroup length] > 0)
  3451. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3452. cell.shared.userInteractionEnabled = NO;
  3453. } else {
  3454. if ([shareLink length] > 0)
  3455. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3456. if ([shareUserAndGroup length] > 0)
  3457. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3458. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3459. [tap setNumberOfTapsRequired:1];
  3460. cell.shared.userInteractionEnabled = YES;
  3461. [cell.shared addGestureRecognizer:tap];
  3462. }
  3463. }
  3464. } else {
  3465. cell.shared.userInteractionEnabled = NO;
  3466. }
  3467. // ----------------------------------------------------------------------------------------------------------
  3468. // downloadFile
  3469. // ----------------------------------------------------------------------------------------------------------
  3470. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3471. cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3472. // sessionTaskIdentifier : RELOAD + STOP
  3473. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3474. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3475. cell.cancelTaskButton.hidden = NO;
  3476. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3477. cell.reloadTaskButton.hidden = NO;
  3478. }
  3479. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3480. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3481. if (progress > 0) {
  3482. cell.progressView.progressTintColor = [UIColor blackColor];
  3483. cell.progressView.progress = progress;
  3484. cell.progressView.hidden = NO;
  3485. }
  3486. // ----------------------------------------------------------------------------------------------------------
  3487. // downloadFile Error
  3488. // ----------------------------------------------------------------------------------------------------------
  3489. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3490. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3491. if ([metadata.sessionError length] == 0)
  3492. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3493. else
  3494. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3495. }
  3496. }
  3497. // ----------------------------------------------------------------------------------------------------------
  3498. // uploadFile
  3499. // ----------------------------------------------------------------------------------------------------------
  3500. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3501. cell.status.image = [UIImage imageNamed:@"statusupload"];
  3502. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3503. cell.cancelTaskButton.hidden = NO;
  3504. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3505. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3506. cell.status.image = [UIImage imageNamed:@"statusstop"];
  3507. cell.reloadTaskButton.hidden = NO;
  3508. cell.stopTaskButton.hidden = YES;
  3509. } else {
  3510. [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3511. cell.stopTaskButton.hidden = NO;
  3512. cell.reloadTaskButton.hidden = YES;
  3513. }
  3514. // se non c'è una preview in bianconero metti l'immagine di default
  3515. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3516. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3517. cell.labelTitle.enabled = NO;
  3518. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3519. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3520. if (progress > 0) {
  3521. cell.progressView.progressTintColor = [UIColor blackColor];
  3522. cell.progressView.progress = progress;
  3523. cell.progressView.hidden = NO;
  3524. }
  3525. // ----------------------------------------------------------------------------------------------------------
  3526. // uploadFileError
  3527. // ----------------------------------------------------------------------------------------------------------
  3528. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3529. cell.labelTitle.enabled = NO;
  3530. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3531. if ([metadata.sessionError length] == 0)
  3532. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3533. else
  3534. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3535. }
  3536. }
  3537. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3538. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3539. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3540. // ======== MGSwipe ========
  3541. if (metadata.favorite)
  3542. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_unfavorite_", nil)] icon:[UIImage imageNamed:@"swipeUnfavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3543. else
  3544. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_favorite_", nil)] icon:[UIImage imageNamed:@"swipeFavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3545. cell.leftExpansion.buttonIndex = 0;
  3546. cell.leftExpansion.fillOnTrigger = NO;
  3547. //centerIconOverText
  3548. MGSwipeButton *favoriteButton = (MGSwipeButton *)[cell.leftButtons objectAtIndex:0];
  3549. [favoriteButton centerIconOverText];
  3550. //Right
  3551. cell.rightButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_delete_", nil)] icon:[UIImage imageNamed:@"swipeDelete"] backgroundColor:[UIColor redColor]], [MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_more_", nil)] icon:[UIImage imageNamed:@"swipeMore"] backgroundColor:[UIColor lightGrayColor]]];
  3552. cell.rightSwipeSettings.transition = MGSwipeTransitionBorder;
  3553. //centerIconOverText
  3554. MGSwipeButton *deleteButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:0];
  3555. MGSwipeButton *moreButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:1];
  3556. [deleteButton centerIconOverText];
  3557. [moreButton centerIconOverText];
  3558. //restore swipeOffset after relod
  3559. CGFloat swipeOffset = [[_statusSwipeCell objectForKey:indexPath] doubleValue];
  3560. if (swipeOffset < 0) {
  3561. [cell showSwipe:MGSwipeDirectionRightToLeft animated:NO];
  3562. [_statusSwipeCell removeObjectForKey:indexPath];
  3563. } else if (swipeOffset > 0) {
  3564. [cell showSwipe:MGSwipeDirectionLeftToRight animated:NO];
  3565. [_statusSwipeCell removeObjectForKey:indexPath];
  3566. }
  3567. return cell;
  3568. }
  3569. - (void)setTableViewFooter
  3570. {
  3571. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3572. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3573. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3574. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3575. UIFont *appFont = [UIFont systemFontOfSize:12];
  3576. footerLabel.font = appFont;
  3577. footerLabel.textColor = [UIColor grayColor];
  3578. footerLabel.backgroundColor = [UIColor clearColor];
  3579. footerLabel.textAlignment = NSTextAlignmentCenter;
  3580. NSString *folders;
  3581. NSString *files;
  3582. NSString *footerText;
  3583. if (_sectionDataSource.directories > 1) {
  3584. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3585. } else if (_sectionDataSource.directories == 1){
  3586. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3587. } else {
  3588. folders = @"";
  3589. }
  3590. if (_sectionDataSource.files > 1) {
  3591. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3592. } else if (_sectionDataSource.files == 1){
  3593. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3594. } else {
  3595. files = @"";
  3596. }
  3597. if ([folders isEqualToString:@""]) {
  3598. footerText = files;
  3599. } else if ([files isEqualToString:@""]) {
  3600. footerText = folders;
  3601. } else {
  3602. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3603. }
  3604. footerLabel.text = footerText;
  3605. [footerView addSubview:footerLabel];
  3606. [self.tableView setTableFooterView:footerView];
  3607. }
  3608. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3609. {
  3610. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3611. // settiamo il record file.
  3612. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3613. if (!_metadata)
  3614. return;
  3615. // se non può essere selezionata deseleziona
  3616. if ([cell isEditing] == NO)
  3617. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3618. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3619. if (self.tableView.editing) {
  3620. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3621. [self setTitle];
  3622. return;
  3623. }
  3624. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3625. if (!serverUrl) return;
  3626. // se è in corso una sessione
  3627. if ([_metadata.session length] > 0) return;
  3628. // file
  3629. if (_metadata.directory == NO) {
  3630. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3631. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3632. #ifdef DEBUG
  3633. // TEST ENCRYPTED
  3634. if ([_metadata.fileName containsString:@".dms"]) {
  3635. [[NCClientEncryption sharedManager] decryptMetadata:_metadata activeUrl:app.directoryUser];
  3636. }
  3637. #endif
  3638. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3639. } else {
  3640. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3641. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3642. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3643. }
  3644. }
  3645. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3646. }
  3647. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3648. {
  3649. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3650. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3651. [self setTitle];
  3652. }
  3653. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3654. {
  3655. if (!indexPath)
  3656. return NO;
  3657. NSInteger section = indexPath.section;
  3658. NSInteger row = indexPath.row;
  3659. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3660. if (section > lastSectionIndex || lastSectionIndex < 0)
  3661. return NO;
  3662. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3663. if (rowCount < 0)
  3664. return NO;
  3665. return row <= rowCount;
  3666. }
  3667. #pragma --------------------------------------------------------------------------------------------
  3668. #pragma mark ===== Navigation ====
  3669. #pragma --------------------------------------------------------------------------------------------
  3670. - (BOOL)shouldPerformSegue
  3671. {
  3672. // if background return
  3673. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3674. if (self.view.window == NO)
  3675. return NO;
  3676. // Collapsed ma siamo già in detail esci
  3677. if (self.splitViewController.isCollapsed)
  3678. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3679. return YES;
  3680. }
  3681. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3682. {
  3683. id viewController = segue.destinationViewController;
  3684. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  3685. tableMetadata *metadata;
  3686. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3687. UINavigationController *nav = viewController;
  3688. _detailViewController = (CCDetail *)nav.topViewController;
  3689. } else {
  3690. _detailViewController = segue.destinationViewController;
  3691. }
  3692. if ([sender isKindOfClass:[tableMetadata class]]) {
  3693. metadata = sender;
  3694. [allRecordsDataSourceImagesVideos addObject:sender];
  3695. } else {
  3696. metadata = _metadata;
  3697. for (NSString *fileID in _sectionDataSource.allEtag) {
  3698. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3699. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [metadata.typeFile isEqualToString: k_metadataTypeFile_audio])
  3700. [allRecordsDataSourceImagesVideos addObject:metadata];
  3701. }
  3702. }
  3703. _detailViewController.metadataDetail = metadata;
  3704. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  3705. _detailViewController.dateFilterQuery = nil;
  3706. [_detailViewController setTitle:metadata.fileName];
  3707. }
  3708. // can i go to next viewcontroller
  3709. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3710. {
  3711. NSString *nomeDir;
  3712. if(self.tableView.editing == NO) {
  3713. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3714. if (!serverUrl) return;
  3715. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  3716. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3717. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  3718. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  3719. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3720. viewController.delegate = self;
  3721. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3722. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3723. viewController.inputViewTitlePassword = YES;
  3724. if ([CCUtility getSimplyBlockCode]) {
  3725. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3726. viewController.passcodeInputView.maximumLength = 6;
  3727. } else {
  3728. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3729. viewController.passcodeInputView.maximumLength = 64;
  3730. }
  3731. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3732. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3733. viewController.touchIDManager = touchIDManager;
  3734. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3735. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3736. //viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3737. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3738. [self presentViewController:navController animated:YES completion:nil];
  3739. return;
  3740. }
  3741. nomeDir = _metadata.fileName;
  3742. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3743. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  3744. if (!viewController) {
  3745. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  3746. viewController.serverUrl = serverUrlPush;
  3747. viewController.titleMain = _metadata.fileName;
  3748. viewController.textBackButton = _titleMain;
  3749. // save self
  3750. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  3751. [self.navigationController pushViewController:viewController animated:YES];
  3752. } else {
  3753. if (viewController.isViewLoaded) {
  3754. // Fix : Application tried to present modally an active controller
  3755. if ([self.navigationController isBeingPresented]) {
  3756. // being presented
  3757. } else if ([self.navigationController isMovingToParentViewController]) {
  3758. // being pushed
  3759. } else {
  3760. [self.navigationController pushViewController:viewController animated:YES];
  3761. }
  3762. }
  3763. }
  3764. }
  3765. }
  3766. @end